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

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -