Go Variable Scope
In Go, variable scope refers to the visibility and accessibility of variables within different parts of a program. The scope of a variable is determined by where it is declared and defined, and it affects how the variable can be accessed and used.
There are three levels of variable scope in Go:
Package-level scope: Variables declared at the package level can be accessed by any function within the same package. These variables are visible to all functions in the package, and they can be accessed using their names.
Function-level scope: Variables declared within a function are only accessible within that function. They are not visible outside the function, and they are destroyed when the function exits. These variables are usually used to store temporary values or intermediate results.
Block-level scope: Variables declared within a block of code (such as an if statement or for loop) are only accessible within that block. They are not visible outside the block, and they are destroyed when the block exits. Block-level variables are also used to store temporary values or intermediate results.
Here's an example that illustrates variable scope in Go:
package main import "fmt" var packageLevelVar int = 10 func main() { var functionLevelVar int = 20 fmt.Println("packageLevelVar =", packageLevelVar) // prints "packageLevelVar = 10" fmt.Println("functionLevelVar =", functionLevelVar) // prints "functionLevelVar = 20" if true { var blockLevelVar int = 30 fmt.Println("blockLevelVar =", blockLevelVar) // prints "blockLevelVar = 30" } // fmt.Println("blockLevelVar =", blockLevelVar) // this line would cause an error because blockLevelVar is out of scope }
In this example, a package-level variable packageLevelVar
is declared and initialized with the value 10
. A function-level variable functionLevelVar
is declared within the main
function and initialized with the value 20
. The values of both variables are printed to the console using the fmt.Println
function.
Inside an if
block, a block-level variable blockLevelVar
is declared and initialized with the value 30
. The value of this variable is also printed to the console. Note that the variable is only accessible within the if
block, and trying to access it outside the block would result in a compile-time error.