The Go loop variable semantics changed in Go 1.22: loop variables are now
created per-iteration instead of per-loop. The compiler decides which
semantics to use based on the Go version in go.mod.
When go.mod specifies go 1.21 and the code is built with a Go 1.22+
compiler, the per-loop(compatible behavior) semantics should be used.
However, when a line directive is present in the source file,
go.mod 1.21 and go1.22+ compiler outputs a per-iteration semantics.
For example, the file below wants output 333 but got 012.
-- go.mod --
module test
go 1.21
-- main.go --
//line main.go:1
func main() {
var fns []func()
for i := 0; i < 3; i++ {
fns = append(fns, func() { fmt.Print(i) })
}
for _, fn := range fns {
fn()
}
}
The distinctVars function uses stmt.Pos().Base() to look up the file
version in FileVersions. Base() returns the file name after line
directives are applied (e.g., "main.go" for "//line main.go:1"), not
the actual source file path. This causes the version lookup to fail
for files with line directives.
This CL fixes the bug by using stmt.Pos().FileBase() instead. FileBase()
returns the actual file path before line directives are applied, ensuring
the correct version information is retrieved from the original source file.
Fixes: #77248
Change-Id: Idacc0816d112ee393089262468a02acfe40e4b72
Reviewed-on: https://go-review.googlesource.com/c/go/+/737820
Reviewed-by: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
The Go Programming Language
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
Gopher image by Renee French, licensed under Creative Commons 4.0 Attribution license.
Our canonical Git repository is located at https://go.googlesource.com/go. There is a mirror of the repository at https://github.com/golang/go.
Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.
Download and Install
Binary Distributions
Official binary distributions are available at https://go.dev/dl/.
After downloading a binary release, visit https://go.dev/doc/install for installation instructions.
Install From Source
If a binary distribution is not available for your combination of operating system and architecture, visit https://go.dev/doc/install/source for source installation instructions.
Contributing
Go is the work of thousands of contributors. We appreciate your help!
To contribute, please read the contribution guidelines at https://go.dev/doc/contribute.
Note that the Go project uses the issue tracker for bug reports and proposals only. See https://go.dev/wiki/Questions for a list of places to ask questions about the Go language.