Puzzle 8 Explanation: Closure
Explore how closure affects goroutines in Go by examining Puzzle 8. Understand why goroutines may use the same variable, and discover two methods to fix this issue: passing variables as parameters or using variable scope to shadow outer variables. This lesson improves your grasp of Go concurrency and variable scoping to avoid common mistakes.
We'll cover the following...
We'll cover the following...
Try it yourself
Try running the code below to see the result for yourself.
Explanation
You probably expected 1 2 3. Each goroutine sleeps n milliseconds and then prints n. We use the wg.Wait() ...