This question already has an answer here:
I want to append to a slice that is a value of a map, e.g. given m map[string][]string
:
if values, exists := m[key]; exists {
values = append(values, v)
// I don't want to call: m[key] = values
} else {
m[key] = []string{ v }
}
That obviously doesn't work, so I tried instead of appending the value as is, to do something like:
valuesPtr := &values
*values = append(values, v)
But that doesn't work either. How can I do that?
</div>
You cannot do that.
append
returns a new slice, since a slice may have to be resized to complete the append. You must update your map to use the newly returned slice, which cannot be done without referencing by key.