Scope

Scope

Variables with the same name can coexist in different scopes.

Lets look at this programm:

  1 package main
  2
  3 import "fmt"
  4
  5 var i = 42
  6
  7 func main() {
  8         i := 40
  9         for true {
 10                 i := 43
 11                 fmt.Println("Scope for:", i)
 12                 i = 44
 13                 fmt.Println("Scope for:", i)
 14                 break
 15         }
 16         fmt.Println("Scope main:", i)
 17         outer()
 18 }
 19
 20 func outer() {
 21         fmt.Println("Function: ", i)
 22 }

In line 5 i is declared for the package level. Unless there is a new i defined in more inner scopes, you will refer to the variable declared in line 5.

In line 8 an variable with scope in the function main is declared. In line 16 we print this variable, although in the for loop another variable with the same name is declared in line 10.

Play around with the exercise 3 to get the concept.

Source

See the full source on github.

Sources