Exercise 3

Exercise 3: Scopes

Create, save and run this file:

package main

import "fmt"

var i = 42

func main() {
	i := 40
	for true {
		i := 43
		fmt.Println("Scope for:", i)
		i = 44
		fmt.Println("Scope for:", i)
		break
	}
	fmt.Println("Scope main:", i)
	outer()
}

func outer() {
	fmt.Println("Function: ", i)
}

Tasks:

  • What will happen if you delete the line i := 43 in the for loop?
  • Will the program still run, if you remove the first definition of i var i = 42?

Source

See the full source on github.

Sources