dongyou2714 2016-06-14 09:32 采纳率: 0%
浏览 74
已采纳

了解Golang中的词法作用域

https://play.golang.org/p/kK9c71Yt9N - This is the code I'm working off of.

I'm trying to understand lexical scoping for the variable X. If I use the := operator in line 11, X defined outside of func main gets hidden and a new scope is getting created within the function. If I use the = operator in the same line, the compiler complains that err is undefined.

My understanding is that the := operator creates variables which are not defined and hence, only err has to get defined. But, this understanding is clearly wrong.

What code changes can I do to make sure X is not redefined within main()?

I know I can do the following to make sure X is not redefined within main():

var err error
X, err = InitX()

Is there a better way that I might be missing?

  • 写回答

1条回答 默认 最新

  • doulu1020 2016-06-14 09:43
    关注

    My understanding is that the := operator creates variables which are not defined and hence, only err has to get defined.

    This is expected and your workaround is OK. It is described in some detail in Effective Go.

    In a := declaration a variable v may appear even if it has already been declared, provided:

    • this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
    • the corresponding value in the initialization is assignable to v, and
    • there is at least one other variable in the declaration that is being declared anew.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探