Luigi
Published on

Understanding scope in Golang

banner

What is scope?

Scope can be defined as the current context of execution in which values and expressions are "visible" or can be accessed within a program. If a variable or expression is not in the current scope,it will not be available for use by other parts of the program.

There exists two types of scope in Go:

Local scope

Local scope is achieved when a variable is declared inside a function body. Such variables are said to have local scope thus (within the function). They can not be accessed outside of the function.

These types of variables are called local variables. For example,

package main
import "fmt"

func printNumber() {

 b := 2

}

func main() {

printNumber()

// b is inaccessible
fmt.Println("Value of b is", b)

}

Global scope

When a variable is declared outside of a function body, it possesses a global scope. Such variables are know as global variables. They can be accessed from any part of a program. For example,


package main
import "fmt"

var x string

func printString () {

x = "This is a string"

}


func main() {

  printString()

  fmt.Println("Value of x is", x)

}

Why is scope important in a program?

  • Scope helps to prevent mutation of assigned values during the lifetime of a program which helps avoid unneccessary bugs in a program.

What happens if a variable has the same name in both the global and local scope?

If we have local and global variables with the same variable names, the compiler gives priority to the local variable. For example,

// Program to illustrate the priorities of variables

package main
import "fmt"

// define global variable
x  := 10

func main() {

 // define local variable with same name
  x := 30

  fmt.Println(random)

}

Output

30

Resources


Let me know what your thoughts are about this article hi[at]luigimorel.com. Cheers!

© 2022 - 2024 Luigi Morel. All rights reserved.