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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?