Why can't you assign arrays inside maps in Go?

Here is a short example to demonstrate:

package main import "fmt" func main() { array := [3]int{1, 2, 3} array[0]++ // Works slice := make([]int, 3) for i := range slice { slice[i] = i + 1 } arrayMap := make(map[int][3]int) sliceMap := make(map[int][]int) arrayMap[0] = array sliceMap[0] = slice //arrayMap[0][0]++ // Does not compile: "cannot assign to arrayMap[0][0]" sliceMap[0][0]++ fmt.Println(arrayMap) fmt.Println(sliceMap) } 

Why can't I change the contents of an array if it is inside the map, even if they change outside the map? And why does this work with slices?

+7
dictionary arrays go
source share
1 answer

For maps, its values โ€‹โ€‹are not addressable. That is, when you use value type (arrays of value types in Go), you cannot address a value using ++ .

But if you use the reference type (fragments of the reference types in Go), you can, as mentioned in the example.

This is true, regardless of the type used on the Map.

The only thing we can do is use the ptr type address. For example, if you take the address of an array, then it should work:

Playground: http://play.golang.org/p/XeIThVewWD

 package main import "fmt" func main() { array := [3]int{1, 2, 3} slice := []int{1, 2, 3} arrayMap := make(map[int]*[3]int) // use the pointer to the type sliceMap := make(map[int][]int) arrayMap[0] = &array // get the pointer to the type sliceMap[0] = slice arrayMap[0][0]++ // works, because it a pointer to the array sliceMap[0][0]++ fmt.Println(*arrayMap[0]) fmt.Println(sliceMap[0]) } // outputs [2 2 3] [2 2 3] 

This works and increases the index [0] from array to 2 , as expected.

This works because Go kindly selects pointers for us to its value when reading and updates the value during re-assignment.

+5
source share

All Articles