Initializing an explicit GO array

Is there an explicit array initialization (declaration and assignment) in GO or the only way to use the shorthand operator? Here is a practical example - these are two equal:

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

var a [3]int = [3]int{1, 0, 1}
+4
source share
1 answer

They are equivalent. In general: Spec: Short variable declaration:

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

This is a shorthand for regularly declaring variables with initializer expressions, but without types:

"var" IdentifierList = ExpressionList .

So this line:

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

This is equivalent to this:

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

[3]int, :

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

Spec: :

, . .

, : [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: :

:

  • , .
  • ; .
  • . , .

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.

. + : golang

+7

Source: https://habr.com/ru/post/1650269/


All Articles