go - Why golang don't iterate correctly in my for loop with range? -
I am confused why the repeated value of the following code is not printed.
test: = [] int {0,1,2,3,4} for i, class = test {go func () {fmt.Println (i, v) }} What do I think should print it
0 0 2 2 3 3 4 4 < P> But instead, it was printed 4 4 4 4 4 4 4 4 Post-text "itemprop =" text "> Your Goroutines variables do not capture the current value of i and v , rather they refer to variables themselves In this case, till the end of five, 5 spanded goratin NSA were not fixed, so all i and v The final values were printed on. If you want to obtain the current values of some variables for gorotine, you can modify the code to read some of the following:
go Func (i, v int) {fmt.println (I, v)} (i, v) Now each gouroutine has its own copy, which it is at the time it was created Holds the value.
Comments
Post a Comment