Scope
Variables declared outside any functions are global in Go,those defined in functions are local to those functions. Ifnames overlap - a local variable is declared with the same name as a global one- the local variable hides the global one when the current function is executed.
In the following example we call g()
from f()
:
package main
var a int 1
func main() {
a = 5
print(a)
f()
}
func f() {
a := 6 2
print(a)
g()
}
func g() {
print(a)
}
Here 1, we declare a
to be a global variable of type int
. Then in themain
function we give the global a
the value of 5, after printing it wecall the function f
. Then here 2, a := 6
, we create a new, local_variable also called a
. This new a
gets the value of 6, which we then print.Then we call g
, which uses the _global a
again and prints a
’s value setin main
. Thus the output will be: 565
. A local variable is only validwhen we are executing the function in which it is defined. Note that the :=
used in line 12 is sometimes hard to spot so it is generally advised not touse the same name for global and local variables.