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 non-negative constant representable by a value of type
int
; and if it is typed it must be of integer type.- An element without a key uses the previous element’s index plus one. If the first element has no key, its index is zero.
Normally, you’ll see the keys omitted in slice and array literals.
var x = []string{"eggs", "bread", "milk"}
But as we see above, the indexes can be included explicitly:
var x = []string{0: "eggs", 1: "bread", 2: "milk"}
Or even specified out of order:
var x = []string{1: "bread", 2: "milk", 0: "eggs"}
Or even a mix of the two:
var x = []string{1: "bread", "milk", 0: "eggs"}
I don’t suggest doing that, though, unless you have a really compelling reason. It will virtually always make your code harder to read.
Quotes from The Go Programming Language Specification Version of August 2, 2023