Go "cannot range over n (variable of type int)" on an older toolchain in CI
Ranging over an integer (for i := range n) became valid in Go 1.22. On an older toolchain, or with a go directive below 1.22, the compiler rejects it as "cannot range over n (variable of type int)".
What this error means
Code that runs locally fails in CI with "cannot range over n (variable of type int)" because the runner Go version, or the module go directive, predates 1.22.
./loop.go:7:14: cannot range over n (variable of type int)Common causes
The CI Go version is older than 1.22
The integer range syntax compiles only on Go 1.22+, so an older runner toolchain rejects it.
The go directive in go.mod is below 1.22
Even on a newer toolchain, a go 1.21 directive disables the 1.22 language feature, so the range form is not accepted.
How to fix it
Use a toolchain and go directive at 1.22 or newer
- Pin setup-go to 1.22 or later.
- Raise the
godirective in go.mod to at least 1.22. - Re-run the build.
- uses: actions/setup-go@v5
with:
go-version: '1.22'Or use a classic loop
If you must support older Go, write the conventional three-clause loop instead of ranging over an int.
for i := 0; i < n; i++ {
// ...
}How to prevent it
- Keep the CI Go version aligned with the language features you use.
- Set the
godirective to match the minimum version your syntax requires. - Run a version matrix so old-toolchain breaks surface in PRs.