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():

  1. package main
  2. var a int 1
  3. func main() {
  4. a = 5
  5. print(a)
  6. f()
  7. }
  8. func f() {
  9. a := 6 2
  10. print(a)
  11. g()
  12. }
  13. func g() {
  14. print(a)
  15. }

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.