Home >Backend Development >Golang >How Does Variable Scope and Shadowing Work in Go?
Variable Scope and Shadowing in Go: A Comprehensive Guide
In Go, understanding variable scope and shadowing is crucial for writing clean and maintainable code. Variable scope defines the visibility of a variable within a program, while shadowing refers to the re-declaration of a variable with the same name in a nested scope.
Variable Scoping in Go
Go uses lexical scoping, meaning that the scope of a variable is determined by its position within the code. There are five different scope levels:
Variable Shadowing in Go
Shadowing occurs when a variable in an inner scope is declared with the same name as a variable in an outer scope. In such cases, the variable in the inner scope takes precedence and shadows the outer variable.
Advantages of Variable Scoping and Shadowing
Different Forms of Variable Shadowing
In Go, variable shadowing can be achieved in several ways:
Using short-hand assignment inside statements:
for i := 'a'; i < 'b'; i++ { // i shadowed inside this block }
Using {...} pairs:
{ i := "hi" //new local var }
Using function calls:
func fun(i int) { i++ //use as local var without side effect }
Shadowing global variables:
var i int = 1 //global func main() { i := 10 //Shadowing global var }
Code Samples and Examples
Variable Scoping:
package main func main() { i := 10 //scope: main fmt.Println(i) //output: 10 }
In this example, i is declared within the main function and is only accessible within that function.
Variable Shadowing:
package main func shadow() { x := 10 //shadowing global variable x fmt.Println(x) //output: 10 } var x int = 1 //global variable func main() { fmt.Println(x) //output: 1 shadow() }
In this example, the global variable x is shadowed by the local variable x in the shadow function. Therefore, when x is accessed inside the shadow function, it refers to the local variable with the value 10.
The above is the detailed content of How Does Variable Scope and Shadowing Work in Go?. For more information, please follow other related articles on the PHP Chinese website!