修改一个作为映射值的数组。

huangapple go评论123阅读模式
英文:

Modify an array that is the value of a map

问题

如果我有一个值为数组的地图,我该如何修改数组的一个元素?

类似这样:

  1. m := make(map[string][4]int)
  2. m["a"] = [...]int{0, 1, 2, 3}
  3. m["a"][2] = 10

这段代码无法编译通过:prog.go:8: cannot assign to m["a"][2]

我可以将变量复制到一个数组中,修改它,然后再将其复制回地图,但这似乎非常慢,特别是对于大数组来说。

  1. // 我想避免的方法。
  2. m := make(map[string][4]int)
  3. m["a"] = [...]int{0, 1, 2, 3}
  4. b := m["a"]
  5. b[2] = 10
  6. m["a"] = b

有什么想法吗?

英文:

If I have a map whose value is an array, how can I modify one element of the array?

Something like this:

  1. m := make(map[string][4]int)
  2. m["a"]=[...]int{0,1,2,3}
  3. m["a"][2]=10

It won't compile: prog.go:8: cannot assign to m["a"][2]

I could copy the variable to an array, modify it and then copying it back to the map, but it seems to be very slow, specially for large arrays.

  1. // what I like to avoid.
  2. m := make(map[string][4]int)
  3. m["a"] = [...]int{0, 1, 2, 3}
  4. b := m["a"]
  5. b[2] = 10
  6. m["a"] = b

Any idea?

答案1

得分: 4

使用指针。例如,

  1. package main
  2. import "fmt"
  3. func main() {
  4. m := make(map[string]*[4]int)
  5. m["a"] = &[...]int{0, 1, 2, 3}
  6. fmt.Println(*m["a"])
  7. m["a"][2] = 10
  8. fmt.Println(*m["a"])
  9. }

输出:

  1. [0 1 2 3]
  2. [0 1 10 3]
英文:

Use a pointer. For example,

  1. package main
  2. import "fmt"
  3. func main() {
  4. m := make(map[string]*[4]int)
  5. m["a"] = &[...]int{0, 1, 2, 3}
  6. fmt.Println(*m["a"])
  7. m["a"][2] = 10
  8. fmt.Println(*m["a"])
  9. }

Output:

  1. [0 1 2 3]
  2. [0 1 10 3]

答案2

得分: 0

你的map值(arrays)是不可寻址的,根据规范

> 每个左操作数必须是可寻址的

如果你真的想使用Arrays,可以尝试@peterSO建议的方法,但我认为在这里使用Slices更加习惯。

英文:

Your map value (arrays) is not addressable, From the spec:

> Each left-hand side operand must be addressable

Go for what @peterSO suggest if you really want to use Arrays, but I think that Slices here are more mush idiomatic.

答案3

得分: 0

如果你将字符串映射到切片而不是数组,这样就可以实现:

  1. m := make(map[string][]int)
  2. m["a"] = []int{0, 1, 2, 3}
  3. fmt.Println(m["a"])
  4. m["a"][2] = 10
  5. fmt.Println(m["a"])
英文:

If you map strings to slices, rather than to arrays, this works:

  1. m := make(map[string][]int)
  2. m["a"] = []int{0, 1, 2, 3}
  3. fmt.Println(m["a"])
  4. m["a"][2] = 10
  5. fmt.Println(m["a"])

huangapple
  • 本文由 发表于 2013年12月30日 01:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/20827771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定