![]() |
VOOZH | about |
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.
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)
}
var variableName type = value
Table of Content
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.
200
Global variables are defined outside any function or block, making them accessible throughout the program.
100
When a local variable shares the same name as a global variable, the local variable takes precedence within its scope.
Local variable takes precedence: 200