Search⌘ K
AI Features

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...

Try it yourself

Try running the code below to see the result for yourself.

Go (1.16.5)
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for _, 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() ...