range语句中的迭代变量每次循环时被重复使用,也就是迭代变量的地址不变,值变。与闭包同时使用时容易出错,看如下代码:
错误用法:
func main() {
data := []string{"one", "two", "three"}
for _, v := range data {
fmt.Printf("v point:%p\n", &v)
go func() {
fmt.Println("v:", v)
}()
}
<-time.After(2 * time.Second)
}
输出:
v point:0xc04200a2a0
v point:0xc04200a2a0
v point:0xc04200a2a0
v: three
v: three
v: three
正确用法一:
func main() {
data := []string{"one", "two", "three"}
for _, v := range data {
temp := v
fmt.Printf("temp point:%p\n", &temp)
go func() {
fmt.Println("v:", temp)
}()
}
<-time.After(2 * time.Second)
}
输出:
temp point:0xc0420381d0
temp point:0xc042038200
temp point:0xc042038210
v: one
v: two
v: three
正确用法二:
func main() {
data := []string{"one", "two", "three"}
for _, v := range data {
go func(str string) {
fmt.Println("v:", str)
}(v)
}
<-time.After(2 * time.Second)
}
v: two
v: three
v: one