Skip to content

x/tools/gopls/internal/analysis/modernize: rangeint suggests changes that alter some programs' semantics #75289

@jub0bs

Description

@jub0bs

Go version

go version go1.25.1 darwin/amd64

Output of go env in your module/workspace:

N/A

What did you do?

I ran modernize (commit 0b1eed0) on the following program (playground), which outputs 10:

package main

import "fmt"

func main() {
	var i int
	defer func() { fmt.Println(i) }()
	for i = 0; i < 10; i++ {
		// deliberately empty
	}
}

What did you see happen?

REDACTED.go:8:6: for loop can be modernized using range over int

Fix suggested:

Replace for loop with range 10

i.e.

 func main() {
        var i int
        defer func() { fmt.Println(i) }()
-       for i = 0; i < 10; i++ {
+       for i = range 10 {
                // deliberately empty
        }
 }

What did you expect to see?

No suggested change, or at least not that one. The semantics of the resulting program are indeed different from the original program's: whereas the original program prints 10, the resulting program (playground) prints 9:

package main

import "fmt"

func main() {
	var i int
	defer func() { fmt.Println(i) }()
	for i = range 10 {
		// deliberately empty
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.ToolsThis label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions