Variable Scopes and Shadowing
Explore Go's variable scopes defined at package, function, and statement levels. Understand variable shadowing, rules for redeclaration, zero values for types, and how Go enforces usage of declared variables to prevent bugs.
We'll cover the following...
A scope is part of the program in which a variable can be seen. In Go, we have the following variable scopes:
-
Package scoped: Can be seen by the entire package and is declared outside a function
-
Function scoped: Can be seen within
{}which defines the function -
Statement scoped: Can be seen within
{}of a statement in a function (forloop,if/else)
In the following program, the word variable is declared at the package level. It can be used by any function defined in the package:
In the following program, the word variable is defined inside the main() function and can only be used inside {} which defines main. Outside, it is undefined:
Finally, in this program, i is statement scoped. It ...