This is the same as Why does go forbid taking the address of (&) map member, yet allows (&) slice element? but I'm not satisfied with the accepted answer: "Slices are backed by a backing array and maps are not."
Note: I have now added my own answer to the referenced question above.
The question Access Struct in Map (without copying) is even better, but its accepted answer says you can't modify a field of a struct value in a map because you cannot take its address (which is my question).
Maps are backed by memory structures (possibly including arrays) just like slices are.
So what is the real reason why I can't take the address of a map value?
I wanted to modify a map struct value in place. Numeric values in maps can be modified in place using operators like ++ or +=
func icandothis() {
cmap := make(map[int]complex64)
cmap[1] += complex(1, 0)
fmt.Println(cmap[1])
}
But struct values cannot be modified:
type Complex struct {
R float32
I float32
}
func (x *Complex) Add(c Complex) {
x.R += c.R
x.I += c.I
}
func but_i_cannot_do_this() {
cmap := make(map[int]Complex)
//cmap[1].Add(Complex{1, 0})
fmt.Println(cmap[1])
}
func so_i_have_to_do_this() {
cmap := make(map[int]Complex)
c := cmap[1]
c.Add(Complex{1, 0})
cmap[1] = c
fmt.Println(cmap[1])
}