Scope is where a variable can be used. A variable can often be used inside a function, a local variable.

Sometimes a variable can be used everywhere in the program, a global variable.

There are also cases in which a variable only exists inside an statement or loop. These are also local variables.

Download PDF

Examples

Local vs global variables

The variable x below is a local variable, it can only be used inside the main() function.

package main

import "fmt"

func main() {
x := 7
fmt.Println(x)
}

If you move the variable x outside of the function, it becomes a global variable.

Global variables can be used by multiple functions. In this example example() and main()

package main

import "fmt"

var x = 7

func example() {
fmt.Println(x)
}

func main() {
fmt.Println(x)
example()
}

Global variables are sometimes considered a bad practice.
When possible, you should pass variables as function parameters instead.

Exercises

  • What’s the difference between a local and global variable?
  • How can you make a global variable?

Download Answers