Go: Who Knows What Evil Lurks in the Hearts of Men?

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:

Makes sense. Now change presidents := 1 to presidents := 2 and you’ll get:

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’spresidents := 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.

So:

  • 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!

Graybeard code monkey, started on an Apple IIe, got a CS degree in the 80’s, and coded my way through C, C++, Objective-C, Java, Kotlin — and now Go.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store