Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Go language variable scope


May 11, 2021 Go


Table of contents


Go language variable scope

Scope is the range of constants, types, variables, functions, or packages represented by declared identifiers in the source code.

Variables in the 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 function definitions are called formal arguments

Let's take a look at local variables, global variables, and formal parameters.


The local variable

Variables declared inside a function are called local variables, and their scope is only within the function body, and parameter and return value variables are also local variables.

The main() function in the following example 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 output of the above examples is:

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

Global variable

Variables declared outside the function are called global variables, which can be used throughout the package or even in external packages (after export).

Global variables can be used in any function, and the following example shows 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 output of the above examples is:

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

The global variables in the Go language program can be the same as the local variable names, but the local variables within the function are given priority. Here's an example:

package main

import "fmt"

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

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

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

The output of the above examples is:

结果: g = 10

Formal parameters

Formal parameters are used as local variables of the function. Here's an example:

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 output of the above examples is:

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

Initialize local and global variables

The default values for different types of local and global variables are:

The data type Initialize the default value
Int 0
float32 0
pointer nil