简体   繁体   中英

golang does not update array in a map

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM