:=
运算符用于初始化值,然后使用=
运算符分配值
var fruits := [5]string{"Apple", "Orange", "Banana", "Grape", "Plum"}
给出语法错误(syntax error: unexpected :=, expecting = go
),
var fruits = [5]string{"Apple", "Orange", "Banana", "Grape", "Plum"}
语法工作正常。
为什么不允许:=
用var
关键字初始化?
答案 0 :(得分:1)
将:=
视为declare and assign
。
来自语言specification:
与常规变量声明不同,简短的变量声明可以重新声明变量,前提是它们最初是在相同类型的同一块中(如果该块是函数体,则在参数列表中)早先声明,且类型相同,并且至少一个-空白变量是新的。因此,重新声明只能出现在多变量简短声明中。重新声明不会引入新变量;只是为原始值分配了一个新值。
field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset) // redeclares offset
a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere