Scope of Variables in Go (original) (raw)

Last Updated : 12 Jul, 2025

Prerequisite: Variables in Go Programming Language

The scope of a variable defines the part of the program where that variable is accessible. In Go, all identifiers are lexically scoped, meaning the scope can be determined at compile time. A variable is only accessible within the block of code where it is defined.

Example

package main
import "fmt"

// Global variable declaration
var myVariable int = 100

func main() {
// Local variable inside the main function
var localVar int = 200
fmt.Printf("Inside main - Global variable: %d\n", myVariable)
fmt.Printf("Inside main - Local variable: %d\n", localVar)
display()
}

func display() {
fmt.Printf("Inside display - Global variable: %d\n", myVariable)
}

Syntax

**var variableName type = value

Table of Content

Local Variables

Local variables are declared within a function or a block and are not accessible outside of it. They can also be declared within loops and conditionals but are limited to the block scope.

Example:

Go `

package main import "fmt"

func main() { var localVar int = 200 // Local variable fmt.Printf("%d\n", localVar) // Accessible here }

`

Global Variables

Global variables are defined outside any function or block, making them accessible throughout the program.

Example:

Go `

package main import "fmt"

// Global variable declaration var myVariable int = 100 // Global variable

func main() { fmt.Printf("%d\n", myVariable) // Accessible here }

`

Local Variable Preference

When a local variable shares the same name as a global variable, the local variable takes precedence within its scope.

Example

Go `

package main import "fmt"

// Global variable declaration var myVariable int = 100 // Global variable

func main() { var myVariable int = 200 // Local variable fmt.Printf("Local variable takes precedence: %d\n", myVariable) // Accesses local variable }

`

Output

Local variable takes precedence: 200