Search⌘ K
AI Features

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.

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:

Go (1.18.2)
package main
import "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:

Go (1.18.2)
package main
import "fmt"
func main() {
var word string = "hello"
fmt.Println(word)
}

Finally, in this program, i is statement scoped. It ...