duanquan4451 2018-12-03 06:17
浏览 18

附加到作为地图中值的切片[重复]

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>
  • 写回答

1条回答 默认 最新

  • drd2551 2018-12-03 06:19
    关注

    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.

    评论

报告相同问题?