Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)
Loop Variable Scoping in Go 1.22: How was the classic closure capture bug resolved?
senior LevelMost AskedClosures & ScopeGolang
In Simple Words:
In Go 1.21 and older, for k, v := range items reused a single variable instance across all loop iterations. Passing &v to a goroutine caused all goroutines to read the value of the final iteration!
In Go 1.22+, loop variables are per-iteration scoped: each iteration gets its own unique variable instance, completely eliminating the need for v := v shadowing.