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? )