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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题