切片slice,是一个指针管理器,指向数据区域。在range 遍历时,获取到的值是一个变量的拷贝,不是迭代器。所以,后面的值会覆盖前面的值。
package mainimport "fmt"func main() {data := []int{1, 2, 3}tbl := []*int{}for _, v := range data {tbl = append(tbl, &v)}fmt.Println("========== probe1 ================")fmt.Println(*tbl[0], *tbl[1], *tbl[2])fmt.Println(tbl[0], tbl[1], tbl[2])tbl = []*int{}for index, _ := range data {tbl = append(tbl, &data[index])}fmt.Println("========== probe2 ================")fmt.Println(*tbl[0], *tbl[1], *tbl[2])fmt.Println(tbl[0], tbl[1], tbl[2])tbl = []*int{}for _, v := range data {vv := vtbl = append(tbl, &vv)}fmt.Println("========== probe3 ================")fmt.Println(*tbl[0], *tbl[1], *tbl[2])fmt.Println(tbl[0], tbl[1], tbl[2])
}
执行结果:
root@ubuntu:~/home
========== probe1 ================
3 3 3
0xc00001a0e0 0xc00001a0e0 0xc00001a0e0
========== probe2 ================
1 2 3
0xc00001e0c0 0xc00001e0c8 0xc00001e0d0
========== probe3 ================
1 2 3
0xc00001a0e8 0xc00001a0f0 0xc00001a0f8
root@ubuntu:~/home