The Shadow Knows…
In programming, there is a situation referred to as variable shadowing. It’s when you reuse a variable name in an inner scope that was already used in an outer scope. The new variable shadows the outer one, and changes made in the inner scope to the variable will not affect the value of the variable in the outer scope.
It’s a simple thing, a valid language feature, here’s an example of variable shadowing:
Running the above you’d see:
Number of presidents: 1
Makes sense. Now change
presidents := 1 to
presidents := 2 and you’ll get:
Shadow Government of: 2
More than one president might as well be 1000
Number of presidents: 2
Maybe that last line surprised you, but it occurred because
presidents := 1000 uses
:= which is a declaration, not an assignment, so it shadows the outer scope’s
presidents := 2 .
How does shadowing impact Go code?
While other languages have more or less control around shadowing, in particular richer support around immutability, Go peaks at const.
- Use declarations vs assignments correctly. Duh.
- Keep variable scopes as tight as possible, regardless of shadowing this is best practice. One nice Go pattern around tight scoping is:
- Employ shadowing very thoughtfully, it negatively impacts readability, while most IDEs will warn you when you do it, the compiler, linter, and code previewing tools may not even mention it!