๐ŸŽ“ A1Learner
๐Ÿ”

Go Scope

Scope is the part of a program where a name can be used. A name declared inside a function can be used only inside that function.

A local variable inside a function

The message variable is declared inside showMessage. That function is the only place where the name exists.

package main

import "fmt"

func showMessage() {
	message := "Inside the function"
	fmt.Println(message)
}

func main() {
	showMessage()
}

Two functions read one package-level variable

The place variable sits outside both functions. Each function reads the same value.

package main

import "fmt"

var place = "Seattle"

func printPlace() {
	fmt.Println(place)
}

func printPlaceAgain() {
	fmt.Println(place)
}

func main() {
	printPlace()
	printPlaceAgain()
}

A local name shadows the outer name

The change function declares its own score with a short declaration. The outer score keeps its value after the call.

package main

import "fmt"

var score = 10

func change() {
	score := 99
	fmt.Println(score)
}

func main() {
	change()
	fmt.Println(score)
}

A local name used outside its function fails

The count variable exists only inside show. Main tries to print that name and the compiler refuses the program.

package main

import "fmt"

func show() {
	count := 42
	fmt.Println(count)
}

func main() {
	show()
	fmt.Println(count)
}

Example

package main

import "fmt"

var counter = 0

func raise() {
	counter++
}

func main() {
	raise()
	raise()
	fmt.Println(counter)
}

Key points

  • A local variable exists only inside the function where it is declared.
  • A package-level variable is declared outside every function.
  • Every function in the package can read a package-level variable.
  • A local declaration with the same name shadows the outer name inside its function.
  • Shadowing changes only what the name means inside that function.

In this example, counter is a package-level variable that starts at zero. The raise function adds one to it on each call. Main calls raise twice, so the printed value is 2.

Note

The compiler refuses a name that is used outside its scope.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

A function declares score := 99 while a package-level score holds 10. What does the package-level score hold after the call?