Scope of a variable in Go


Scope of a variable in Go

In this tutorial, we are going to discuss scope of a variable in Go language. We can make a variable declaration in Go language at the package level, function level, or block level. The scope of a variable defines from where we can access that variable and the variable’s lifetime.

Go language variables can be divided into two categories based on the scope.

  1. Local Variable
  2. Global Variable
Scope of a variable in Go
Local Variable
  • Local variables are variables that are defined within a block or a function level.
  • An example of a block is a for loop or a range loop etc.
  • Local variables are only be accessed from within their block or function.
  • A local variable, once declared, cannot be re-declared within the same block or function.
  • These variables only live till the end of the block or a function in which they are declared. After that, they are Garbage Collected.

Example

package main

import "fmt"

func main() {
    var message = "Welcome to Waytoeasylearn"
    fmt.Println(message)
    for i := 0; i < 3; i++ {
        fmt.Println(i)
    }
    fmt.Println(i)
}

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

Output

./prog.go:11:17: undefined: i
./prog.go:15:17: undefined: message

Run in playground

In the above example,

  • Local or loop variable i is not available after the for loop.
  • Similarly, the local variable message is not available outside the function in which it is declared.
Global Variable
  • A variable will be global within a package if it is declared at the top of a file outside the scope of any function or block.
  • If the variable name starts with a lowercase letter, it can be accessed from within the package that contains this variable definition.
  • If the variable name starts with an uppercase letter, it can be accessed outside of the package.
  • Global variables are available throughout the lifetime of a program.

For example, in the below program variable message will be a global variable available throughout the main package. It will be available in any function inside the main package.

Please note that the variable name will not be available outside the main package as its name starts with a lowercase letter.

package main

import "fmt"

var message = "Welcome to Waytoeasylearn"

func main() {
	testLocal()
}

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

Output

Welcome to Waytoeasylearn

Run in playground

Note

A variable declared within an inner scope having the same name as the variable declared in the outer scope will shadow the variable in the outer scope..

package main

import "fmt"

var message = "Welcome to Waytoeasylearn"

func main() {
    var message = "Welcome to Waytoeasylearn Golang tutorials"
    fmt.Println(message)
}

Output

Welcome to Waytoeasylearn Golang tutorials

Run in playground

Scope of a variable in Go
Scroll to top