Puzzle 8 Explanation: Closure
Understand how wait() works in Go.
We'll cover the following...
We'll cover the following...
Try it yourself
Try running the code below to see the result for yourself.
Go (1.16.5)
package mainimport ("fmt""sync""time")func main() {var wg sync.WaitGroupfor _, n := range []int{3, 1, 2} {wg.Add(1)go func() {defer wg.Done()time.Sleep(time.Duration(n) * time.Millisecond)fmt.Printf("%d ", n)}()}wg.Wait()fmt.Println()}
Explanation
You probably expected 1 2 3
. Each goroutine sleeps n
milliseconds and then prints n
. We use the wg.Wait()
...