In a pub quiz by Dave Cheney I came across the following construct:
a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4}
fmt.Println(a)
>> [5 4 3 2 1 0]
It seems you can use keys in the initialization fields of an array (4: 1, 0
means set element at index 4 to 1, element at index 5 to 0). I have never seen something like this before. What is its use case? Why not set the particular index directly?
In composite literals the key (index in case of array and slice literals) can be optionally provided.
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:
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:
Another example: let's create a slice which tells if a day is weekend; Monday being 0, Tuesday being 1, ... and Sunday being 6:
Or even better, you can even omit the 2nd index (
6
) as it will be implicitly6
(previous +1):If your array indices are sparse, it's shorter than doing
{1,0,0,0,0,2,0,0,0,0,3}
etc, and it's shorter than multiple assignment lines, so I'm guessing that's the use case.I've never seen this syntax used before anywhere.