Array and slice literals

September 27, 2023

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

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content

Composite keys

This week’s episode of the Cup o’ Go podcast is out! Keep up with the Go community in just 15 minutes per week! Have a listen! Composite literals … The key is interpreted as a field name for struct literals, an index for array and slice literals, and a key for map literals. For map literals, all elements must have a key. If you’ve written any Go code, you probably already know about keys in maps:

Assignability of composite components

Composite literals … The types of the elements and keys must be [assignable(] to the respective field, element, and key types of type T; there is no additional conversion. This shouldn’t be surprising, but let’s examine the implications just the same. type myStr string s := myStr("my string") var x = map[int]string{ 3: "oink", // Valid, untyped numeric constant 3 is assignable to an int. int(4): "quack", // Valid, int(4) is of type int int64(12): "moo", // Invalid, int64(12) is not converted to int 8: s, // Invalid, type myStr is type string 9: string(s), // Valid; explicit conversion to type string } Quotes from The Go Programming Language Specification Version of August 2, 2023

Composite literals

Earlier this year, near the beginning of this series on the Go spec, we went through literal representations of all of the basic types in Go: ints, strings, etc. If this were an Intro to Go style book, the very next section would have been on composite literals. But it’s not. So we had to wait nearly 6 months to get to that topic… But here we are, at long last!