A problem encountered when assigning values to go and python variables: gopython variable assignment
I usually write a lot about python. I recently read a little bit about go. I encountered a problem today. I 'd like to share it with you.
package mainimport "fmt"type student struct { Name string Age int}func pase_student() { m := make(map[string]*student) stus := []student{ {Name: "zhou", Age: 24}, {Name: "li", Age: 23}, {Name: "wang", Age: 22}, } for _, stu := range stus { m[stu.Name] = &stu } fmt.Println(m["zhou"].Name)}func main() { pase_student()}
The code is very simple. You can think about what will be printed.
Time. sleep (60) # Thoughts
The result is wang !, No surprises! Traverse assignment. Students, this simple operation can generate a moth, WTF!
Why is it wang?
You tm to me
Explanations
What is surprise?
:
During a for loop, the stu pointer of the variable remains unchanged. Each loop only copies the value of the student struct. The above for loop is the same as the following:
var stu student for _, stu = range stus { m[stu.Name] = &stu}
So & stu is an address from start to end, and the value stored on this address is changed. The final storage value of & stu is the student {Name: "wang", Age: 22} struct, so the result is wang.
Let's take a look at m:
map[zhou:0xc42000a260 li:0xc42000a260 wang:0xc42000a260]
The above ideas are verified, and all values are the same address.
As you can see, a person who writes strong types of languages such as c and c ++ may say, it's a mental illness! What can I say about this! Isn't that the case! Forgive me for writing python [cover your face].
As shown in the preceding example, in go, the variable name is the name of the storage address. It has been bound during compilation and cannot be changed during runtime. You can only change the value stored in the address.
In python, the variable is the object name, and the variable can be bound to any object during runtime. As follows:
In [4]: a = 123456In [5]: id(a)Out[5]: 4426596208In [6]: a = 1234567In [7]: id(a)Out[7]: 4426592592
Note: Because python implements a small integer Object pool for the int type, do not use an integer ranging from 0 to 255 for the experiment. Otherwise, the id will be the same.
That is to say, when you loop through a list, each time you get a different object, the variable points to a different address:
In [9]: for i in [2222, 2223, 2224]: ...: print(id(i)) ...:442659620844265923364426596080
In the above Code, python creates three py1_bject for us. I is just their name. In go, we can think that there is only one object, and the value has changed three times.
The value assignment in python is to create an object reference, which is the truth.