Maps with slices as values
suggest changem := make(map[string][]int)
fmt.Printf("Non-existing key returns zero value of []int, i.e. nil: %#v\n", m["key1"])
m["key1"] = append(m["key1"], 8)
m["key1"] = append(m["key1"], 3)
fmt.Printf("\nAfter appending to slice: %#v\n", m["key1"])
delete(m, "key1")
fmt.Printf("\ndelete() sets back to nil slice: %#v\n", m["key1"])
Non-existing key returns zero value of []int, i.e. nil: []int(nil)
After appending to slice: []int{8, 3}
delete() sets back to nil slice: []int(nil)
Notice that in m["key1"] = append(m["key1"], 8)
we don't have to check if m["key1"]
exists. This is a result of interplay of 3 rules:
m["foo"]
returns zero-value iffoo
key is not present is the map- zero-value of slice is
nil
a = append(nil, 3)
is valid and creates a single-element slice[]int{3}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents