mmcgrana / gobyexample

Go by Example
https://gobyexample.com
7.16k stars 1.26k forks source link

Local Variable Captured by Func Literal in `waitgroups` Example #535

Closed AndrewLawrence80 closed 3 months ago

AndrewLawrence80 commented 3 months ago

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)
}
eliben commented 3 months ago

Duplicate of https://github.com/mmcgrana/gobyexample/issues/520