# Go語言作用域規則

1. 在函數或塊中聲明的爲局部變量。
2. 在所有函數之外聲明的變量稱爲全局變量。
3. 在定義函數參數變量時，稱爲形參。

## 局部變量

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

## 形式參數

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

nil