Search⌘ K
AI Features

Scope of Variables

Explore the concept of variable scope in Go including global and local scopes. Understand the difference between value and reference types and how memory is managed for each. Learn to apply these concepts to avoid errors and write clear, efficient Go programs.

Scope of a variable

A variable of any type is only known in a certain range of a program, called its scope. In a programming language, there are two main types of scopes:

  • Global scope
  • Local scope

Global scope

The scope of the variables declared outside of any function (in other words at the top level) is called global scope. Global scope is also known as package scope because the variables with such scope are visible and available in all source files of a package.

Local scope

The scope of the variables declared inside a function is called local scope. They are only known in that function; the same goes for parameters and return variables of a function.

In simple words, mostly, you can think of a scope as the code block ( surrounded by { } ) in which the variable is declared. Run the following program to visualize the concept of scope.

Go (1.6.2)
package main
import "fmt"
var number int = 5 // number declared outside (global scope)
func main(){
var decision bool = true // decision declared inside function(local scope)
fmt.Println("Original Value of number: ",number)
number = 10 // reassigning the number
fmt.Println("New Value of number: ",number)
fmt.Println("Value of decision: " ,decision)
}
  • Line 4: Let’s first
...