range 是进行的深拷贝,并且迭代的变量(index和value)的指针地址是不变的。
range 可以迭代 array、slice、string(range迭代的是Unicode而不是字节,所以返回的值是rune)、map、channel。
package main
import "fmt"
func main() {
slices1 := []int{1, 2, 3}
for index, value := range slices1 {
fmt.Printf("%d => %d\n", index, value)
fmt.Println(&index, &value)
}
fmt.Println("========== 坑 ==========")
// 错误使用方式
copyedList := make([]*int, len(slices1))
for i, value := range slices1 {
copyedList[i] = &value
}
fmt.Println("错误输出", copyedList)
// 正确使用方法
copyedList = make([]*int, len(slices1))
for i := range slices1 {
copyedList[i] = &slices1[i]
}
fmt.Println("正确输出", copyedList)
fmt.Println("========== 指针数组 ==========")
// 指针数组 这个也需要注意
slices2 := make([]*int, 3)
for i := 0; i < 3; i++ {
n := i + 1
slices2[i] = &n
}
for index, value := range slices2 {
fmt.Printf("%d => %d\n", index, *value)
fmt.Println(&index, &value, value)
}
}
0 => 1
0xc00010c008 0xc00010c010
1 => 2
0xc00010c008 0xc00010c010
2 => 3
0xc00010c008 0xc00010c010
========== 坑 ==========
错误输出 [0xc00010c030 0xc00010c030 0xc00010c030]
正确输出 [0xc000118020 0xc000118028 0xc000118030]
========== 指针数组 ==========
0 => 1
0xc00010c050 0xc000100020 0xc00010c038
1 => 2
0xc00010c050 0xc000100020 0xc00010c040
2 => 3
0xc00010c050 0xc000100020 0xc00010c048