Go 1.21 includes a preview of a change to for loop scoping that will be implemented in Go 1.22, aimed at addressing a common mistake in Go programming. The mistake involves keeping a reference to a loop variable beyond its iteration, resulting in unexpected values. The problem can occur with or without goroutines. This mistake has caused issues at various companies, including Lets Encrypt. Tools have been developed to identify the mistake, but they struggle to provide accurate results. To fix this problem, Go 1.22 will introduce per-iteration scope for loop variables. The change will be backward compatible and can be gradually adopted in existing codebases. A preview of the fix is included in Go 1.21. The precision of the loopclosure analyzer has also been improved in this version to help identify problematic code.
https://go.dev/blog/loopvar-preview