It’s Monday again. That means I’ll be live-coding again! I hope you can join me.
Composite literals
…
The length of an array literal is the length specified in the literal type. If fewer elements than the length are provided in the literal, the missing elements are set to the zero value for the array element type. It is an error to provide elements with index values outside the index range of the array. The notation
...
specifies an array length equal to the maximum element index plus one.buffer := [10]string{} // len(buffer) == 10 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 days := [...]string{"Sat", "Sun"} // len(days) == 2
The included examples are helpful, but we can expand a bit further:
var x = [10]string{0: "foo", 3: "bar", "baz", 2: "qux"} // Remember, we can specify index keys, if we want to.
Now here’s a quiz:
What does the following code print?
var hmm = [...]int{1, 2, 3, 12: 9, 8: 3}
fmt.Println(len(hmm))
Quotes from The Go Programming Language Specification Version of August 2, 2023