GO显式数组初始化

GO explicit array initialization

GO 中是否有明确的数组初始化(声明和赋值)或唯一的方法是使用 shorthand 运算符? 这是一个实际的例子——这两个是否相等:

a := [3]int{1, 0, 1}

var a [3]int = [3]int{1, 0, 1}

它们是等价的。一般来说:Spec: Short variable declaration:

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

It is shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

所以这一行:

a := [3]int{369, 0, 963}

相当于:

var a = [3]int{369, 0, 963}

但是由于表达式列表是[3]int类型的composite literal,下面是一样的:

var a [3]int = [3]int{369, 0, 963}

Spec: Variable declaration:

If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment.

所以你可以使用以下任何一种,都声明并初始化一个[3]int类型的变量:

a := [3]int{369, 0, 963}
b := [...]int{369, 0, 963}
var c = [3]int{369, 0, 963}
var d [3]int = [3]int{369, 0, 963}
var e [3]int = [...]int{369, 0, 963}
var f = [...]int{369, 0, 963}

备注:

请注意,在复合文字中,不列出所有值是有效的。未明确指定值的元素将是元素类型的 zero value。您可以在枚举中的值之前包含一个可选索引,以指定它将成为其值的元素。

Spec: Composite literals:

For array and slice literals the following rules apply:

  • Each element has an associated integer index marking its position in the array.
  • An element with a key uses the key as its index; the key must be a constant integer expression.
  • An element without a key uses the previous element's index plus one. If the first element has no key, its index is zero.

由于您的初始数组包含一个 0,它是元素类型 int 的零值,您可以将其从文字中排除。要创建一个变量并将其初始化为值 [3]int{369, 0, 963},您也可以这样做:

// Value at index 1 implicitly gets 0:
g := [3]int{369, 2: 963} 
h := [...]int{369, 2: 963} 

尝试 Go Playground 上的所有示例。

详见本题+实例: