为什么golang在我的for循环中没有正确迭代?

A-l*_*bby 1 go goroutine

我很困惑为什么以下代码不打印出迭代值.

test:= []int{0,1,2,3,4}
for i,v := range test{
  go func(){
    fmt.Println(i,v)
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为它应该打印出来

0 0
1 1
2 2
3 3 
4 4
Run Code Online (Sandbox Code Playgroud)

但相反,它打印出来了

4 4
4 4
4 4
4 4
4 4
Run Code Online (Sandbox Code Playgroud)

Jam*_*dge 9

你够程不捕获变量的当前值iv,而是它们引用变量本身.在这种情况下,5个生成的goroutine在for循环完成之前没有进行调度,因此所有打印出的最后一个值为iv.

如果要捕获gouroutine的某些变量的当前值,可以修改代码以读取如下内容:

go func(i, v int){
    fmt.Println(i,v)
}(i, v)
Run Code Online (Sandbox Code Playgroud)

现在每个gouroutine都有自己的变量副本,在变量生成时保存该值.