Paul Krill
Editor at Large

Go language fixes for loop issue

news
Feb 07, 20242 mins
Google GoProgramming LanguagesSoftware Development

A change to the implementation of for loops in Go 1.22 avoids accidental sharing bugs. Runtime optimization also is enhanced in update.

Google’s Go (golang) language has reached version 1.22, bringing changes to for loops including a resolution to problem that risked the accidental sharing of loop variables.

Released February 6, Go 1.22 can be downloaded and installed from go.dev. Release notes for Go 1.22 can be found on the project website. 

With Go 1.22, the Go team has resolved what has been called the for loop “gotcha,” leading to accidental sharing of loop variables. In Go 1.22, each iteration of the loop builds new variables to avoid accidental sharing bugs. In a second change, for loops in Go can now range over integers. 

Also in Go1.22, a runtime optimization improves CPU performance by 1% to 3% while reducing memory overhead of most Go programs by about 1%. Improved devirtualization in profile-guided optimization (PGO) builds also is featured, allowing static dispatch of more interface method calls. Most programs will see improvements of 2% to 14% with PGO enabled. PGO was introduced in Go 1.21, which arrived in August 2022.

Go 1.22 also brings improvements to the standard library. A math/rand/v2 package provides a more consistent and cleaner API and uses higher-quality, faster pseudo-random generation algorithms. Also, HTTP routing patterns used by net/http.ServeMux now accept wild cards and methods.

Elsewhere in Go 1.22:

  • Go commands in workspaces now can use a vendor directory containing dependencies of the workspace.
  • The trace tool’s web UI has been refreshed as part of the work to support the new tracer, resolving several issues and improving the readability of various sub-pages.
  • The behavior of the vet tool has changed to match the new semantics of loop variables in Go 1.22. Also, vet now reports a non-deferred call to time.Since (t) within a defer statement.
  • On macOS on 64-bit architecture, the Go toolchain now generates position-independent executables by default.
  • Go 1.22 adds an experimental port to OpenBSD on big-endian 64-bit PowerPC.