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:
var x = map[string]float64{
"key1": 1.0,
"key2": 2.0,
"keyπ": 3.14159,
}
What’s maybe slightly less obvious, but not surprising, is that the field names in structs are also called keys, in a composite literal:
var x = struct {
Key1 string
Key2 int
}{
Key1: "neat",
Key2: 15,
}
What’s less known… and in fact, I didn’t even realize it, or I had forgotten, until I was preparing to write this… is that slice and array literals can include keys as well. In such a case, the keys must be integers, and indicate the index of the value. This allows you to specify slice/array values out of order, if for some reason you wish to, or to sparsely populate a slice or array.
var x = []string{
1: "foo",
5: "bar",
2: "baz",
}
fmt.Println(strings.Join(x,",")) // Prints: ,foo,baz,,,bar
Quotes from The Go Programming Language Specification Version of August 2, 2023