1. 程式人生 > 其它 >go變數與常量

go變數與常量

變數

變數宣告

一般形式的變數宣告,可以同時宣告多個同類型變數,初始化為預設值或者可以手動賦初始值。

// case1
var identifier type
// case2
var identifier1, identifier2 type
// case3
var identifier1, identifier2 int = 1, 2

型別自動推導,可以同時宣告多個不同型別的變數。

// case1
var identifier = 1
// case2
var identifier1, identifier2 = 1, "hello"
// case3
var (
	identifier1 = 1
	identifier2 = "hello"
)

簡短型別宣告,等號左邊必須包含至少一個新的變數名,不然會報錯。

// case1
identifier := 1
// case2
identifier1, identifier2 := 1, "hello"

作用域與變數覆蓋

當進入子作用域的時候,可以使用同名的變數,這時可以起到覆蓋的作用。

func main() {
	n := 1
	{
		n := "hello"
		fmt.Println(n) // 輸出hello
	}
	fmt.Println(n) // 輸出1
}

這個規則遇到簡短型別宣告多個變數的時候也是成立的,子作用域中還是新的變數。

func main() {
	n, m := 1, 2
	{
		n, k := 3, 4
		fmt.Println(n, k) // 輸出3, 4
	}
	fmt.Println(n, m) // 輸出1, 2
}

常量

常量宣告

常量的宣告和變數是一樣的,只是前面的var換成了const,並且常量必須在宣告的時候賦初值。

// case1
const identifier int = 1
// case2
const identifier1, identifier2 int = 1, 2
// case3
const identifier = 1
// case4
const identifier1, identifier2 = 1, "hello"
// case5
const (
	identifier1 = 1
	identifier2 = "hello"
)

iota

在上面case5中,常量可以不指定右側的表示式,但第一個常量名必須指定,忽略右側表示式的常量相當於重寫了一遍上一個常量右側的表示式。

const (
    thumb = 1
    index
    middle = 2
    ring
    pinky
)

fmt.Println(thumb, index, middle, ring, pinky) // 輸出1 1 2 2 2

iota在go中是特殊的關鍵字,表示常數生成器。iota從0開始,每隔一行就增加1。

const (
    thumb = iota
    index
    middle
    ring
    pinky
)

fmt.Println(thumb, index, middle, ring, pinky) // 輸出0 1 2 3 4

中途使用iota,這裡就看出iota其實就是代表當前所在行數。

const (
    thumb = 100
    index
    middle = iota
    ring
    pinky
)

fmt.Println(thumb, index, middle, ring, pinky) // 輸出100 100 2 3 4

參考資料