Today, when writing code, encountered a baffling error, debug a half-day, found that this is a very typical and easy to make mistakes. Remember it
Example code:
Package Mainimport"FMT"type AAstruct{x, yint}type BBstruct{member Aa}func main () {m:= []*aa{} pool:=[]BB {member:aa{x:1Y:1,},}, {member:aa{x:2Y:2,},}, {member:aa{x:3Y:3,}, }, } for_, P: =Range Pool {m= Append (M, &p.member)} for_, Ele: =range m {ele.x= ele.x +1Ele.y= Ele.y +1 } for_, Ele: =range M {fmt. Printf ("x=%d, y=%d\n", ele.x, Ele.y)}}
What is the result of the above code? Perhaps you will immediately answer is:
x=2, y=2
X=3, y=3
X=4, y=4
Run it and know that the answer is wrong. The correct operation results are:
X=6, y=6
X=6, y=6
X=6, y=6
So what's wrong? Originally in the array m, its three elements are the same pointer. Originally in the following code, Golang is a new variable p, each time the elements of the array
Assigned to this p, and the address of P is naturally constant, so the last element in M is the address of the member variable member of this p.
for _, P: = range Pool { = append (M, &p.member) }
This example tells us that in an iterative operation of array/map in Golang, be careful if you need to access pointers to the array/map elements in the iteration. This type of bug is very difficult to detect.
The pointers in the pits in the Golang are used