# Go - 作用域

• 在函数或块内( local 变量)

无涯教程网

• 所有函数之外( global变量)

• 在函数参数中( formal参数)

## 局部变量

```package main

import "fmt"

func main() {
/* local variable declaration */
var a, b, c int

/* actual initialization */
a=10
b=20
c=a + b

fmt.Printf ("value of a=%d, b=%d and c=%d\n", a, b, c)
}```

`value of a=10, b=20 and c=30`

## 全局变量

```package main

import "fmt"

/* global variable declaration */
var g int

func main() {
/* local variable declaration */
var a, b int

/* actual initialization */
a=10
b=20
g=a + b

fmt.Printf("value of a=%d, b=%d and g=%d\n", a, b, g)
}```

`value of a=10, b=20 and g=30`

```package main

import "fmt"

/* global variable declaration */
var g int=20

func main() {
/* local variable declaration */
var g int=10

fmt.Printf ("value of g=%d\n",  g)
}```

`value of g=10`

## 参数变量

Formal参数在该函数中被视为局部变量，并且它们优先于全局变量。如-

```package main

import "fmt"

/* global variable declaration */
var a int=20;

func main() {
/* local variable declaration in main function */
var a int=10
var b int=20
var c int=0

fmt.Printf("value of a in main()=%d\n",  a);
c=sum( a, b);
fmt.Printf("value of c in main()=%d\n",  c);
}
/* function to add two integers */
func sum(a, b int) int {
fmt.Printf("value of a in sum()=%d\n",  a);
fmt.Printf("value of b in sum()=%d\n",  b);

return a + b;
}```

```value of a in main()=10
value of a in sum()=10
value of b in sum()=20
value of c in main()=30```

int 0
float32 0
pointer nil