* 打印three, three, three
```
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
data := []field{{"one"}, {"two"}, {"three"}}
for _, v := range data {
go v.print()
}
time.Sleep(3 * time.Second)
//goroutines print: three, three, three
}
```
* 打印one, two, three
```
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
data := []*field{{"one"}, {"two"}, {"three"}}
for _, v := range data {
go v.print()
}
time.Sleep(3 * time.Second)
//goroutines print: one, two, three
}
```
第一个打印三个three,表示理解,因为for迭代的时候变量会被重新使用,最终打印的是引用最后一个变量的值,但是为什么第二部分的代码是打印one, two, three,而不是打印three,three,three?
有疑问加站长微信联系(非本文作者)