I am switching from Python to GoLang. I was learning goroutines. I faced strange outputs when I used the goroutines in for loop.
package main
import "fmt"
func main() {
var test = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
for _, x := range test{
go func() {
fmt.Println(x)
}()
}
}
the output:
25
19
28
19
40
40
6
I was thinking it was capturing values from for loop but, when I saw it was increasing and decreasing. I got confused. Why is that happening?