Golang在映射中无法更新数组。

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

golang does not update array in a map

问题

m := map[int][2]int{1:{0,10}}
m[1][0] = 1	

我期望上面的代码像这样工作:

a := [2]int{0,10}
a[0] = 1

但实际上它会报错 cannot assign to m[1][0]

可能的解释是什么?

附注:我知道可以通过声明一个 int 到切片的映射来解决这个问题。

英文:
m := map[int][2]int{1:{0,10}}
m[1][0] = 1	

I expect the above to work like this

a := [2]int{0,10}
a[0] = 1

but instead it gives the following error cannot assign to m[1][0]

What could be a possible explanation for this?

P.S. I know I can get around the problem by declaring a map of int to slice instead of int to array.

答案1

得分: 4

[翻译结果]
赋值的左操作数必须是可寻址的,一个映射索引表达式或空白标识符。

m[1][0]是不可寻址的。请参阅规范以获取可寻址的内容列表。映射值不在该列表中。

表达式m[1][0]是一个数组索引表达式,而不是映射索引表达式。

要更新映射中的值,请将映射值赋给一个变量(该变量是可寻址的),更新变量并重新赋值给映射:

t := m[1]
t[0] = 1
m[1] = t

另一种方法是使用指向[2]int的指针映射:

m := map[int]*[2]int{1: {0, 10}}
m[1][0] = 1

由于隐式指针间接引用,数组元素是可寻址的。

英文:

The left-hand operand of an assignment must be addressable, a map index expression or the blank identifier.

The value m[1][0] is not not addressable. See the specification for a list of what is addressable. A map value is not in that list.

The expression m[1][0] is an array index expression, not a map index expression.

To update the value in the map, assign the map value to a variable (which is addressable), update the variable and assign back to the map:

t := m[1]
t[0] = 1
m[1] = t

Another approach is to use a map of pointers to [2]int:

m := map[int]*[2]int{1: {0, 10}}
m[1][0] = 1

The array elements are addressable because of the implicit pointer indirection.

huangapple
  • 本文由 发表于 2021年10月7日 11:41:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69475165.html
匿名

发表评论

匿名网友

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

确定