Due to my background in Python development, I have little knowledge and have not learned Pointers, memory and other knowledge. Now when I convert to Golang, I will step on some Pointers and other pits. In this chapter, I will record the pits I have stepped on
for… The range of the pit
When writing a for loop with golang, it is important to note that the variable followed by the for loop is always the same pointer address! See code for details
package main
import (
"fmt"
)
func main(a) {
sList := []string{"1"."2"."3"}
for _, v := range sList {
fmt.Printf("%p \n", &v)
}
}
Copy the code
Output results (each output has a different address, but all three lines have the same value)
0xc00000e1e0
0xc00000e1e0
0xc00000e1e0
Copy the code
This tells you that when Go runs the for loop, variables created on the for statement (such as v) use the same memory address each time, and a serious error occurs when you do the following
func pase_student(a) {
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)
}
Copy the code
The output
map[zhou:0xc00000a080 li:0xc00000a080 wang:0xc00000a080]
Copy the code
Three values in this map point to the same memory address! This is obviously not what we want, so we need an extra assignment if we have one of the above:
func pase_student(a) {
m := make(map[string]*student)
stus := []student{
{Name: "zhou", Age: 24},
{Name: "li", Age: 23},
{Name: "wang", Age: 22}},for _, stu := range stus {
st := stu
m[stu.Name] = &st
}
fmt.Println(m)
}
Copy the code
This prevents the above problem, because the value created in the for loop block (such as a) will be a different memory address each time the loop progresses
When we’re writing code, we really have to figure out when to use Pointers and when not to use Pointers, because otherwise it’s very easy to have the kind of problem that I had, right
This article mainly records their own in the development process of the pit, if misunderstood, welcome to comment ~