Scope in programming languages defines the region where a variable exists. In Go, we have three places to declare variables, local, global, and formal parameters. In this article, we will learn Scope Rules in Go.
Local variables are defined inside a function or a block, the brackets {}
. For example, in our main entry point function, all variables we declare exist there and cant be accessed outside.
func main() {
var a int = 1
var b int = 2
}
func sum() {
// Can not access a or b directly
}
Global variables are declared outside of functions and can be accessed by any function. Here is an example of declaring global variables and notice how both our main
and sum
function have access.
package main
import "fmt"
// global
var count int
func sum() {
fmt.Println(count)
}
func main() {
count = 2
fmt.Println(count)
sum()
}
One thing to note is that if you declare local variables with the same name, the local variable will be used instead. For example, let's create a variable called count
inside of sum
.
// global
var count int
func sum() {
count := 5
fmt.Println(count) // Will use local and print 5
}
func main() {
count = 2
fmt.Println(count) // Will print 2
sum()
}
Formal parameters are similar to local variables, but are declared on a function. For example, let's add some parameters to our sum
function.
func sum(a int, b int) {
// a and b are local to sum, but initialized wherever sum is called
fmt.Println(a + b)
}
func main() {
sum(1, 2)
}
You can run the full example code by copying the code below to a file called main.go
and run go run main.go
package main
import "fmt"
// global
var count int
func sum(a int, b int) {
fmt.Println(count)
fmt.Println(a + b)
}
func main() {
count = 2
fmt.Println(count)
sum(1, 2)
}