Variable Scopes and Shadowing
Understand variable scopes and shadowing in Go, along with an overview of zero values.
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 (for
loop,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:
package mainimport "fmt"var word = "hello"func main() {fmt.Println(word)}
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:
package mainimport "fmt"func main() {var word string = "hello"fmt.Println(word)}
Finally, in this program, i
is statement scoped. It can ...