Go 1.22: A Change in Loop Scoping

· Source: HackerNoon · Field: Technology & Digital — Software Development & Engineering · Depth: Intermediate, medium

Summary

Go 1.21 introduces a preview of a significant change to `for` loop scoping, slated for full release in Go 1.22, to address a common programming mistake. Currently, loop variables in Go have per-loop scope, leading to issues where references to a loop variable past its iteration capture an unintended, later value. This problem manifests in concurrent goroutines, where all routines might print the final value of the loop variable, and in non-concurrent scenarios like deferred function calls. The fix, which will apply to packages declaring `go 1.22` or later in their `go.mod` files, will assign per-iteration scope to loop variables, resolving these bugs. Go 1.21 allows developers to preview this change by setting `GOEXPERIMENT=loopvar`, a feature Google has tested internally since May 2023 with no production issues. This change also helps identify and correct buggy tests that inadvertently pass due to the old loop variable semantics.

Key takeaway

For Go developers preparing for Go 1.22, you should test your existing codebase with `GOEXPERIMENT=loopvar` in Go 1.21. This will expose latent bugs in your tests or production code that rely on the current per-loop variable scoping. Addressing these issues now will ensure a smoother transition to Go 1.22's new semantics and prevent unexpected behavior once the change is fully implemented in your modules.

Key insights

Go 1.22 will introduce per-iteration `for` loop variable scoping to prevent common closure-related bugs.

Principles

Method

The `GOEXPERIMENT=loopvar` flag in Go 1.21 enables per-iteration loop variable scoping for testing, ignoring `go.mod` declarations, to preview Go 1.22 behavior.

In practice

Topics

Best for: Software Engineer

Related on AIssential

Open in AIssential →

Editorial summary, takeaway, and curation by AIssential. Original article published by HackerNoon.