In the interest of learning more about Go, I played with goroutines and noticed something - but I'm not sure what I see, and I hope that someone there can explain the following behavior.
The following code does exactly what you expect:
package main import ( "fmt" ) type Test struct { me int } type Tests []Test func (test *Test) show() { fmt.Println(test.me) } func main() { var tests Tests for i := 0; i < 10; i++ { test := Test{ me: i, } tests = append(tests, test) } for _, test := range tests { test.show() } }
and prints 0 - 9, in order.
now that the code is changing as shown below, it always returns with the last first - it doesn't matter which numbers I use:
package main import ( "fmt" "sync" ) type Test struct { me int } type Tests []Test func (test *Test) show(wg *sync.WaitGroup) { fmt.Println(test.me) wg.Done() } func main() { var tests Tests for i := 0; i < 10; i++ { test := Test{ me: i, } tests = append(tests, test) } var wg sync.WaitGroup wg.Add(10) for _, test := range tests { go func(t Test) { t.show(&wg) }(test) } wg.Wait() }
this will return: 9 0 1 2 3 4 5 6 7 8
the iteration order of the loop does not change, so I assume it has something to do with goroutines ... basically, I'm trying to understand why it behaves this way ... I understand that goroutines can work in a different order than the order, in which they are generated, but, my question is, why does this always work like that. as if there is something really obvious there, I miss ...
source share