Go language variable scope
The scope is the scope of the constant, type, variable, function or package represented by the declared identifier in the source code.
Variables in Go language can be declared in three places:
- Variables defined in a function are called local variables
- Variables defined outside the function are called global variables
- Variables in a function definition are called formal parameters
Next, let's learn about local variables, global variables and formal parameters.
local variable
Variables declared in the function body are called local variables. Their scope is only in the function body, and parameters and return value variables are also local variables.
In the following example, the main() function uses local variables a, b, c:
//10scopeRules.go package main import "fmt" func main() { //Declare local variables var a, b, c int //Initialization parameters a = 10 b = 20 c = a + b fmt.Printf ("result: a = %d, b = %d and c = %d\n", a, b, c) }
Operation results:
global variable
Variables declared outside the function are called global variables. Global variables can be used in the whole package or even external packages (after being exported).
Global variables can be used in any function. The following example demonstrates how to use global variables:
//10scopeRules2.go package main import "fmt" //Declare global variables var g int func main() { //Declare local variables var a, b int //Initialization parameters a = 10 b = 20 g = a + b fmt.Printf ("result: a = %d, b = %d and g = %d\n", a, b, g) }
Operation results:
In Go language programs, the names of global variables and local variables can be the same, but local variables in functions will be given priority. Examples are as follows:
//10scopeRules3.go package main import "fmt" //Declare global variables var g int = 20 func main() { //Declare local variables var g int = 10 fmt.Printf ("result: g = %d\n", g) }
Operation results:
Formal parameters
Formal parameters are used as local variables of the function. Examples are as follows:
//10scopeRules4.go package main import "fmt" //Declare global variables var a int = 20 func main() { //Declare local variables in main function var a int = 10 var b int = 20 var c int = 0 fmt.Printf("main()In function a = %d\n", a); c = sum(a, b) fmt.Printf("main()In function c = %d\n", c); } //Function definition - adding two numbers func sum(a, b int) int { fmt.Printf("sum() In function a = %d\n", a); fmt.Printf("sum() In function b = %d\n", b); return a + b }
Operation results:
Initialize local and global variables
The default values of different types of local and global variables are:
data type | Initialize defaults |
---|---|
int | 0 |
float32 | 0 |
pointer | nil |
Reference: https://www.w3cschool.cn/go/