记录for循环中的小坑

for range循环for i, v := range []data{}中, v只初始化一次,也就是它的指针地址在for循环中是不变的。
所以在第二个程序的pase_student()函数中的for循环,获取到的指针地址都是相同的。所以输出结果是相同的。
所以在for循环中,如果涉及到指针,一定要谨慎。

package main
import (
        "fmt"
)
type student struct {
        Name string
        Age  int
}
func pase_student() map[string]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
        }
        return m
}
func main() {
        students := pase_student()
        for k, v := range students {
                fmt.Printf("key=%s,value=%v \n", k, v)
        }
}
package main
import (
        "fmt"
)
type student struct {
        Name string
        Age  int
}
func pase_student() map[string]*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
        }
        return m
}
func main() {
        students := pase_student()
        for k, v := range students {
                fmt.Printf("key=%s,value=%v \n", k, v)
        }
}

你可能感兴趣的:(golang)