go

Understanding scope in Golang

luigimorel

Luigi Morel

Posted on October 17, 2022

Understanding scope in Golang

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

💖 💪 🙅 🚩
luigimorel
Luigi Morel

Posted on October 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024