Maps with slices as values
suggest change m := make(map[string][]int)
fmt.Printf("A missing key returns the zero value of []int, 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("\nAfter delete, lookup returns a nil slice: %#v\n", m["key1"])
A missing key returns the zero value of []int, nil: []int(nil)
After appending to slice: []int{8, 3}
After delete, lookup returns a nil slice: []int(nil)
In m["key1"] = append(m["key1"], 8), there is no need to check whether
m["key1"] exists. Three rules make this work:
m["foo"]returns the value type's zero value when"foo"is absent- the zero value of a slice is
nil - appending to a nil slice is valid and produces a non-nil slice
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents