Scope of Variables in Go
Last Updated :
01 Nov, 2024
Improve
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:
package main
import "fmt"
func main() {
var localVar int = 200 // Local variable
fmt.Printf("%d\n", localVar) // Accessible here
}
Output
200
Global Variables
Global variables are defined outside any function or block, making them accessible throughout the program.
Example:
package main
import "fmt"
// Global variable declaration
var myVariable int = 100 // Global variable
func main() {
fmt.Printf("%d\n", myVariable) // Accessible here
}
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
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