When learning the pointer encountered a problem, posted on the Internet, received a lot of guidance and patience of the predecessors, thank you, and therefore organized this article.
for the first experiment, the code is as follows :
type Student struct { Name string}func remove(stu *Student) { fmt.Printf("2----%v\n", stu) stu = nil fmt.Printf("3----%v\n", stu)}func main() { stu := &Student{"中国"} fmt.Printf("1----%v\n", stu) remove(stu) fmt.Printf("4----%v\n", stu)}
It starts with the understanding that because remove passes in a pointer, Stu=nil, the Stu in main can be set to NULL, but the actual execution results are as follows:
1---- &{中国}2---- &{中国}3---- <nil>4---- &{中国}
The second experiment, the code is as follows:
func remove(stu *Student) { fmt.Printf("2----%p\n", stu) stu = nil fmt.Printf("3----%p\n", stu)}func main() { stu := &Student{"中国"} fmt.Printf("1----%p\n", stu) remove(stu) fmt.Printf("4----%p\n", stu)}
Print the contents of the pointer and perform the following if:
1----0xc0420321d02----0xc0420321d03----0x04----0xc0420321d0
The pointer content is found to be the same, and the third step is to set the pointer content to nil, but the fourth step pointer content remains unchanged.
The third experiment, the code is as follows:
func remove(stu *Student) { fmt.Printf("2----%v\n", &stu) stu = nil fmt.Printf("3----%v\n", &stu)}func main() { stu := &Student{"中国"} fmt.Printf("1----%v\n", &stu) remove(stu) fmt.Printf("4----%v\n", &stu)}
Print the contents of the pointer as follows:
1----0xc04206a0182----0xc04206a0283----0xc04206a0284----0xc04206a018
To this end, we finally find the reasons, summarized as follows:
- In the go language, when a function parameter is a pointer, the value is also passed. (What is value passing: A value pass means that a copy of the actual parameter is passed to the function when the function is called, so that if the parameters are modified in the function, the actual parameters will not be affected)
- When the function parameter is a pointer, the pointer is copied a copy attached to the function, so the above example, main and remove in the two pointers are different addresses (see the third experiment, pointer to the pointer), but they all point to the same student object, So the address stored in the pointer is the same (see Second experiment).
- Fmt. The%p in printf is the address stored in the print pointer, not the location of the fingerprint pointer itself.
- Main is a different two pointer from remove, and when we call Stu=nil in remove, it simply changes the contents of the pointer stored in remove and has no effect on the pointer in main.
Address transfer and pointer comprehension in go language