Go language variable scope
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 within a function are called local variables
Variables defined outside the function are called global variables
Variables in the function definition are called formal parameters
Let us learn more about local variables in detail , global variables and formal parameters.
Local variables
Variables declared in the function body are called local variables. Their scope is only within the function body. Parameter and return value variables are also local variables.
In the following example, the main() function uses local variables a, b, c:
package main import "fmt" func main() { /* 声明局部变量 */ var a, b, c int /* 初始化参数 */ a = 10 b = 20 c = a + b fmt.Printf ("结果: a = %d, b = %d and c = %d\n", a, b, c) }
The execution output result of the above example is:
结果: a = 10, b = 20 and c = 30
Global variables
Variables declared outside the function are called global variables. Global variables can be used in the entire package or even in external packages (after being exported).
Global variables can be used in any function. The following example demonstrates how to use global variables:
package main import "fmt" /* 声明全局变量 */ var g int func main() { /* 声明局部变量 */ var a, b int /* 初始化参数 */ a = 10 b = 20 g = a + b fmt.Printf("结果: a = %d, b = %d and g = %d\n", a, b, g) }
The execution output of the above example is:
结果: a = 10, b = 20 and g = 30
Global in Go language program Variables and local variables can have the same name, but local variables within a function will be given priority. The example is as follows:
package main import "fmt" /* 声明全局变量 */ var g int = 20 func main() { /* 声明局部变量 */ var g int = 10 fmt.Printf ("结果: g = %d\n", g) }
The execution output of the above example is:
结果: g = 10
Formal parameters
Formal parameters will be used as local variables of the function. The example is as follows:
package main import "fmt" /* 声明全局变量 */ var a int = 20; func main() { /* main 函数中声明局部变量 */ var a int = 10 var b int = 20 var c int = 0 fmt.Printf("main()函数中 a = %d\n", a); c = sum( a, b); fmt.Printf("main()函数中 c = %d\n", c); } /* 函数定义-两数相加 */ func sum(a, b int) int { fmt.Printf("sum() 函数中 a = %d\n", a); fmt.Printf("sum() 函数中 b = %d\n", b); return a + b; }
The execution output result of the above example is:
main()函数中 a = 10 sum() 函数中 a = 10 sum() 函数中 b = 20 main()函数中 c = 30
Initialize local and global variables
The default values of different types of local and global variables are:
Data type | Initialize default value |
---|---|
int | 0 |
float32 | 0 |
nil |