drmg17928 2012-07-08 11:39
浏览 60
已采纳

Go中的短变量声明和长变量声明之间的闭包范围有什么区别?

From my reading of the spec:

A short variable declaration ... is a shorthand for a regular variable declaration with initializer expressions but no types...

http://golang.org/ref/spec

I would have thought the two were identical:

var f func()
f = func() {
    ...
}

and

f := func() {
    ...
}

But it seems like they're not. I was trying to wrap a self-recursive function inside of an outer function, but this works:

func myOuter() {
    var f func()

    f = func() {
        f()
    }

    f()
}

But this doesn't, saying undefined: f in the inner function.

func myOuter() {
    f := func() {
        f()
    }

    f()
}

So what is the difference? Is there any way to write this with the short-form declaration or I do I have to write it out long-hand?

  • 写回答

2条回答 默认 最新

  • donglizhan7848 2012-07-08 12:16
    关注

    f := func() { /* ... */ } is identical to var f func() = func() { /* ... */ } (but only the later one is allowed at the package level). In your specific case, neither of the two variants will work, since the statement will be evaluated from right to left. The solution is - as you have already suggested - to split the statement into two. One for declaring the variable and another for assigning the recursive function to it.

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

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据