A loop variable identifies the current iteration. When a goroutine uses that variable after the loop advances, the value may have been overridden, so protect it before launching concurrent work. section 9.5.1
Protect loop variables in three common ways:
- Use a Go version that guarantees safe loop-variable behavior. section 9.7
- Shadow the variable inside the loop: p := p. The goroutine then captures the safe local copy. section 9.5.1
- Pass the variable as a parameter to the anonymous function that starts the goroutine. section 9.5.1
Concurrent path exploration
A maze solver ranges over paths received from a channel and launches one goroutine per path. Passing p directly to the anonymous function or shadowing it prevents later channel messages from changing the path being explored. The same issue appears with map keys, map values, slice elements, and parallel table tests. section 9.5.1 section 9.7
for p := range s.pathsToExplore {
p := p
wg.Add(1)
go func() {
defer wg.Done()
// use the local p
s.explore(p)
}()
...
Shows the shadowing pattern that gives each goroutine its own loop-variable copy. section 9.5.1

