Original: https://haobook.readthedocs.io/zh_CN/latest/periodical/201611/zhangan.html
---------------------------------------------
table of Contents
You can not modify the member variable map
At the beginning of the code when you want to modify the design of the original members of the struct variable or replaced.
Code Example below
package main
import "fmt"
var m = map[string]struct{ x, y int } {
"foo": {2, 3}
}
func main() {
m["foo"].x = 4
fmt.Printf("result is : %+v", m)
}
This thought will be m [ "foo"] is replaced by x 4, thereby printing out the effect is
result is : map[foo:{x:4 y:3}]
However, not of this code compile time after saving tips
cannot assign to struct field m["foo"].x in map
This is embarrassing, it can not change the value of the key nodes already exist, which is Why?
m already exists "foo" this node ah,
Then went to google search the next, and then see on github was mentioned this issue, question address issue-3117
ianlancetaylor answer explanation is given a more able to understand.
It simply is not a map of concurrent security structure, so that he does not modify the value in the structure.
If this current form can not be changed, then we are faced with two options,
1. modify the original design;
2. find a way to map the member variables can be modified,
Because of this structure is the lazy, on the choice of method 2,
But it does not support this way of passing values, how should the member variable map changes now in existence in the struct it?
Enthusiastic users who actually provide a way, for example:
package main
import "fmt"
var m = map[string]struct{ x, y int } {
"foo": {2, 3}
}
func main() {
tmp := m["foo"]
tmp.x = 4
m["foo"] = tmp
fmt.Printf("result is : %+v", m)
}
Sure enough, and expected results are consistent, however, always felt a little strange,
Since it is a temporary space using a similar manner, we use the address referenced by value is not the same as it ...
So we use another way to deal with this thing,
Examples are as follows:
package main
import "fmt"
var m = map[string]*struct{ x, y int } {
"foo": &{2, 3}
}
func main() {
m["foo"].x = 4
fmt.Println("result is : %+v \n", m)
fmt.Println("m's node is : %+v \n", *m["foo"])
}
The final results show:
result is : map[foo:0xc42000cff0]
m's node is : {4, 3}
Thanks so after some agonizing, I know, next time he wanted to map the inside of the struct member variables change, the direct use of address bar.