问题
I am confused why the following code does not print out iterated value.
test:= []int{0,1,2,3,4}
for i,v := range test{
go func(){
fmt.Println(i,v)
}
}
What I think is that it should print out
0 0
1 1
2 2
3 3
4 4
But instead, it printed out
4 4
4 4
4 4
4 4
4 4
回答1:
Your goroutines don't capture the current value of the variables i
and v
, but rather they reference the variables themselves. In this case, the 5 spawned goroutines did not get scheduled until the for loop finished, so all printed out the last values of i
and v
.
If you want to capture the current values of some variables for the gouroutine, you could modify the code to read something like the following:
go func(i, v int){
fmt.Println(i,v)
}(i, v)
Now each gouroutine has its own copy of the variables holding the value at the time it was spawned.
来源:https://stackoverflow.com/questions/21822527/why-golang-dont-iterate-correctly-in-my-for-loop-with-range