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.
eduncan911
source share