var
功能:變量聲明
聲明變量並賦值。
可通過go內部的類型判斷,自動推斷出變量類型,即隱式類型聲明
。
若不明確賦值,則會對變量賦其對應類型的默認值,即默認賦值
。
可同時對同類型的多變量同時賦值,即平行賦值
。
適用範圍
可聲明
全局變量
或局部變量
用法示例
var foo int = 1 //foo == 1, type: int 顯式類型聲明 & 顯式賦值
var foo int //foo == 0, type: int 顯式類型聲明 & 默認賦值
var foo = 1 //foo == 1, type: int 隱式類型聲明 & 顯式賦值
var foo, bar int = 1, 2 //foo == 1, type: int bar == 2, type: int 平行賦值 & 顯式類型聲明 & 顯式賦值
var foo, bar int //foo == 0, type: int bar == 0, type: int 平行賦值 & 顯式類型聲明 & 默認賦值
var foo, bar = 1, 2 //foo == 1, type: int bar == 2, type: int 平行賦值 & 隱式類型聲明 & 顯式賦值
//其他數據類型示例
type Structer struct{
A int
B string
}
var bar Structer //bar == {A:0 B:}, type: Structer 完全等價於:var bar Structer = Structer{}
:=
功能:短變量聲明
聲明局部變量並賦值。
不可指定變量類型。
必須顯式賦值。
可同時對同類型的多變量同時賦值。
適用範圍
只能於函數內部創建
局部變量
。
用法示例
func myFunc() {
foo1 := 1 //foo1 == 1, type: int 隱式類型聲明 & 顯式賦值
foo2, bar2 := 1, 2 //foo2 == 1, type: int bar2 == 2, type: int 平行賦值 & 隱式類型聲明 & 顯式賦值
//其他數據類型示例
bar3 := Structer{} //bar == {A:0 B:}, type: Structer
fmt.Println(foo1, foo2, bar2, bar3)
}
type Structer struct {
A int
B string
}