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?
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.