VOOZH about

URL: https://www.geeksforgeeks.org/go-language/scope-of-variables-in-go/

⇱ Scope of Variables in Go - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scope of Variables in Go

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 

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:


Output
200

Global Variables

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

Example:


Output
100

Local Variable Preference

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

Example


Output
Local variable takes precedence: 200
Comment
Article Tags:

Explore