DEV Community

Cover image for Understanding scope in Golang
Luigi Morel
Luigi Morel

Posted on

Understanding scope in Golang

#go

This article first appeared on my personal website https://luigimorel.co

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)

}
Enter fullscreen mode Exit fullscreen mode

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)

}
Enter fullscreen mode Exit fullscreen mode

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)
}

Enter fullscreen mode Exit fullscreen mode

Output

30
Enter fullscreen mode Exit fullscreen mode

Resources

Top comments (0)