dream0776 2017-07-23 18:03
浏览 90
已采纳

匿名go函数可以调用自身吗?

I'm just running through the Tour of Go, and got to the tree walker exercise. Its obvious recursion, but closing the channel is a special case after the final pop off the call stack. Anyway, I ended up implementing it thusly:

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    var walker func(t *tree.Tree, ch chan int)
    walker = func(t *tree.Tree, ch chan int) {
        if (t.Left != nil) {
            walker(t.Left, ch)
        }
        ch <- t.Value
        if (t.Right != nil) {
            walker(t.Right, ch)
        }
    }
    walker(t, ch)
    close(ch)
}

So far my impression of go is that they prefer to avoid saying things if they can, so the declaration of var walker before the definition seems off. Perhaps I missed some detail that would allow a function to refer to itself without the declaration? It would be a little nicer if it could be:

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    func(t *tree.Tree, ch chan int) {
        if (t.Left != nil) {
            __me__(t.Left, ch)
        }
        ch <- t.Value
        if (t.Right != nil) {
            __me__(t.Right, ch)
        }
    }(t, ch)
    close(ch)
}

This is a simple trivia question, but I'm new enough to the language that I am not finding the answer...

  • 写回答

3条回答 默认 最新

  • douxie2007 2017-07-23 18:13
    关注

    You cannot use a variable before it is declared, and it is not yet declared inside its initialization statement.

    So yes, the declaration line is required, and no, there is no way to avoid it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog