1

Can anyone explain this behavior to me?

package main

import (
    "fmt"
    "time"
)

func main() {
    a := []int64{1, 2, 3, 4, 5}
    for _,v := range a {
        go func(){
            fmt.Println("value is ", v)
        }()
            
    }
    time.Sleep(2*time.Second)
    
}

this code prints the following output.

value is  5
value is  5
value is  5
value is  5
value is  5

Why does the goroutine take only the last value in the slice when no input parameter is passed?

Edit: I just want to know how the program is executing. Every goroutine is having the same value, but why is it always the last value? (Doubt: does goroutine execute only after looping through all the elements in slice? )

Sruthi CP
  • 341
  • 3
  • 13
  • 2
    There is only one `v`, which changes value on every iteration of the loop. You are also possibly reading and modifying `v` at the same time here, which is a race condition. So the actual result will not be well defined. – super Nov 16 '21 at 07:06
  • 1
    Pass the value of `v` as an argument value to the goroutine – Inian Nov 16 '21 at 07:07
  • 2
    Duplicate. Even covered in the official FAQ. – Volker Nov 16 '21 at 07:16

1 Answers1

2

Because each of the goroutines hold the same variable v. If you want to take diffrent value of the silce, do like this:

func main() {
a := []int64{1, 2, 3, 4, 5}
for _,v := range a {
    v2 := v
    go func(){
        fmt.Println("value is ", v2)
    }()

}
time.Sleep(2*time.Second)

}

Output is:

value is  1
value is  2
value is  3
value is  4
value is  5
Infosunny
  • 459
  • 4
  • 17