Latest web development tutorials

Go language variable scoping

Claimed constant scope identifier represented by the type, variable, function, or package scope in the source code.

Go language variables can be declared in three places:

  • Variables defined within a function called local variables
  • Variable outside the function definition is called a global variable
  • Function definition variable called formal parameters

Let us understand the specific local variables, global variables and formal parameters.


Local variables

Called local variables in the variable declaration of the function body, they only function in vivo scope, parameters and return values ​​of variables are local variables.

The following example 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)
}

Examples of the implementation of the above output is:

结果: a = 10, b = 20 and c = 30

Global Variables

Called global variables in the variable declaration of the function in vitro, global variables can (after being exported) using the entire package even external package.

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)
}

Examples of the implementation of the above output is:

结果: a = 10, b = 20 and g = 30

Go language program in global variables and local variables can be the same name, but local variables within the function will be given priority. Examples are as follows:

package main

import "fmt"

/* 声明全局变量 */
var g int = 20

func main() {
   /* 声明局部变量 */
   var g int = 10

   fmt.Printf ("结果: g = %d\n",  g)
}

Examples of the implementation of the above output is:

结果: g = 10

Formal parameters

Form parameter as a function of local variables used. Examples are 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;
}

Examples of the implementation of the above output is:

main()函数中 a = 10
sum() 函数中 a = 10
sum() 函数中 b = 20
main()函数中 c = 30

Initialize local and global variables

Local and global variables of different types of defaults:

type of data Default initialization
int 0
float32 0
pointer nil