news.volyx.in

Fixing for loops in Go 1.22 (go.dev)

598 points by todsacerdoti · 1070 days ago · 455 comments on HN

Article summary

The Go team plans to change the scoping of for loops in Go 1.22 to fix a common mistake where the loop variable is referenced after its iteration. This change will only apply to new or updated code, with old code remaining unaffected. The new semantics can be previewed in Go 1.21 by setting the GOEXPERIMENT environment variable. This change aims to prevent production problems caused by this mistake and remove the need for imprecise tools that prompt unnecessary code changes.

Main themes

  • Go 1.22 changes
  • for loop scoping
  • backwards compatibility
  • code maintenance
  • language design
  • bug fixing

What commenters say

  • The change may break existing code that relies on the current behavior, even if it's a bug.
  • The change is a good fix for a common pitfall, and the backwards compatibility promise is not broken because developers can opt-in to the new behavior.
  • Some argue that the change breaks the Go1 compatibility promise, as programs may not work with future point releases without updates.
  • The change is necessary to fix a real design flaw, and the impact on existing projects will be minimal.
  • The new behavior can be controlled on a per-file basis using //go:build lines, giving developers flexibility in adopting the change.
  • The Go team's approach to backwards compatibility is careful and considered, with a focus on minimizing breakage.
  • Some developers are concerned that the change may cause issues with existing code, even if it's a bug, and that the logic to not compile future versions is wrong.