Go Concurrency Using closures with goroutines in a loop

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

When in a loop, the loop variable (val) in the following example is a single variable that changes value as it goes over the loop. Therefore one must do the following to actually pass each val of values to the goroutine:

for val := range values {
    go func(val interface{}) {
        fmt.Println(val)
    }(val)
}

If you were to do just do go func(val interface{}) { ... }() without passing val, then the value of val will be whatever val is when the goroutines actually runs.

Another way to get the same effect is:

for val := range values {
    val := val
    go func() {
        fmt.Println(val)
    }()
}

The strange-looking val := val creates a new variable in each iteration, which is then accessed by the goroutine.



Got any Go Question?