In the example, the worker call closure captures local variable i, which is not recommended.
Original code:
for i := 1; i <= 5; i++ {
wg.Add(1)
// Wrap the worker call in a closure that makes sure to tell
// the WaitGroup that this worker is done. This way the worker
// itself does not have to be aware of the concurrency primitives
// involved in its execution.
go func() {
defer wg.Done()
worker(i)
}()
}
Improved code:
for i := 1; i <= 5; i++ {
wg.Add(1)
// Wrap the worker call in a closure that makes sure to tell
// the WaitGroup that this worker is done. This way the worker
// itself does not have to be aware of the concurrency primitives
// involved in its execution.
go func(id int) {
defer wg.Done()
worker(id)
}(i)
}
In the example, the worker call closure captures local variable
i
, which is not recommended.Original code:
Improved code: