Welcome To Golang By Example

Scope of a variable in Go (Golang)

Scope of a Variable (Local and Global Variable)

A variable declaration can be done at the package level or a function level or a block level. The scope of a variable defines from where that variable can be accessed and also the lifetime of the variable. Golang variables can be divided into two categories based on the scope.

Local Variable:

See below example

Hence below program will raise a compiler error

undefined: i
undefined: aaa.  #this occurs in the testLocal() function

Code:

package main

import "fmt"

func main() {
    var aaa = "test"
    fmt.Println(aaa)
    for i := 0; i < 3; i++ {
        fmt.Println(i)
    }
    fmt.Println(i)
}

func testLocal() {
    fmt.Println(aaa)
}

Global Variable

For example, in the below program variable aaa will be a global variable available throughout the main package. It will be available in any function inside the main package. Do note that the variable name will not be available outside main package as its name starts with a lowercase letter.

package main

import "fmt"

var aaa = "test"

func main() {
    testGlobal()
}

func testGlobal() {
    fmt.Println(aaa)
}

Output:

test

Important Points

package main

import "fmt"

var a = 123

func main() {
    var a = 456
    fmt.Println(a)
}

Output:

456