Keyed items in golang array initialization

In composite literals the key (index in case of array and slice literals) can be optionally provided.

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.

Elements get the zero value of the element type whose value is not specified.

You can use this to:

  • more compactly initialize arrays and slices if the array/slice has many zero values and just a few non-zero values

  • skip (“jump over”) contiguous parts when enumerating elements, and the skipped elements will be initialized with the zero values

  • specify the first couple of elements, and still specify the length (max index + 1) you want the array/slice to have:

      a := []int{10, 20, 30, 99:0} // Specify first 3 elements and set length to 100
    

The spec also contains an example: create an array which tells if a character is a vowel. This is a very compact and talkative way to initialize the array:

// vowels[ch] is true if ch is a vowel
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}

Another example: let’s create a slice which tells if a day is weekend; Monday being 0, Tuesday being 1, … and Sunday being 6:

weekend := []bool{5: true, 6: true} // The rest will be false

Or even better, you can even omit the 2nd index (6) as it will be implicitly 6 (previous +1):

weekend := []bool{5: true, true} // The rest will be false

Leave a Comment