-2

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?

isapir
  • 14,475
  • 6
  • 82
  • 97
  • Check out https://stackoverflow.com/questions/46492318/go-append-directly-to-slice-found-in-a-map – jmoney Dec 03 '18 at 06:20

1 Answers1

3

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.

Raghav Sood
  • 79,170
  • 20
  • 177
  • 186
  • What if I know the maximum possible capacity and I create the slices to be large enough? Or, is it possible to create a map with values of arrays instead of slices? Would I be able to use pointers then? – isapir Dec 03 '18 at 06:35
  • 3
    @isapir, the capacity doesn't matter here. The length of the slice changes when you append a value, making it a different value, even if the underlying array wasn't relocated. – Peter Dec 03 '18 at 08:34
  • Should I delete this question? There are 2 downvotes so unless it is voted up to at least 0 I think I will remove it. Interestingly there are upvotes for the answer so that seems useful to some (including myself). – isapir Nov 25 '19 at 17:49