go: `:=` operator causes accidental shadowing
January 14, 2016
:= operator to make declaring variables easier. It is a shorthand to declare and set a value of a variable. for example,
can be written as
But if not careful, this can accidently shadow variable bindings. Let’s look at the fictitious piece of code.
This produces following output
value of x: 42
While, this following piece of code will fail to compile
prog.go:12: x redeclared in this block previous declaration at prog.go:10
So we can see that the operator is somewhat intelligent, and does not redeclare the variables.
Now what if we push it down a scope? See the following code
At line: 16, since the immediate scope (line:15-32) does not have variable
:= is redeclaring the variable. a.k.a the variable
x gets shadowed.
Only workaround I can think of is not to use
:=, i.e change the code to
If you know something better let me know.