Engineering Blog


Variable Shadowing in Go

As a part of this blog post, I will try to explain about variable shadowing and how to avoid it. In programming, scope of variable defines to the places a variable can be referenced. In Golang, a variable name declared in a block can be redeclared in an inner block. This mechanism is called variable shadowing. Sometimes, developer may face unintended side effects due to use of shadowed variable. Actually, in shadowed variable allocate the different memory address (address space) that’s why shadowed variable does not effect the outer variable.

Suppose if you declare the count variable inside any function or method and again redeclared same count variable inside the decision block also known as shadowed variable. Following example, try to make clear concept about shadowed variable.

In this example, we first declare a count variable. Then, we use the short variable declaration operator (:=) to redeclared same count variable in inner decision block to assign value 0. But inner count variable not effect the outer count variable. As a result, the outer variable is always print 0 instead of print 1.

NOTE : This code compiles because the inner decision block count variables are used to increment the value. If not, we would have compilation errors such as count declared but not used.

How can we ensure that a value is assigned to the original count variable?

The first approach uses temporary variables in the inner blocks this way:

The second approach uses the assignment operator (=) in the inner block to directly assign the value.

Instead of assigning to a temporary variable first, we can directly assign the result to

Finally, both approaches are perfectly valid. The main difference between the two alternatives that we use only one assignment in the second approach, which may be considered easier to read.


  • Teiva Harsanyi, Go Mistakes and how to avoid them, Manning Publications Co

Previous Post
Next Post