Skip to content
Latchkey

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.

go build
./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

  1. Pin setup-go to 1.22 or later.
  2. Raise the go directive in go.mod to at least 1.22.
  3. Re-run the build.
.github/workflows/ci.yml
- 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.

loop.go
for i := 0; i < n; i++ {
	// ...
}

How to prevent it

  • Keep the CI Go version aligned with the language features you use.
  • Set the go directive to match the minimum version your syntax requires.
  • Run a version matrix so old-toolchain breaks surface in PRs.

Frequently asked questions

What causes ""cannot range over ... (variable of type int)""?
The integer range syntax compiles only on Go 1.22+, so an older runner toolchain rejects it.
How do I fix "cannot range over ... (variable of type int)"?
Use a toolchain and go directive at 1.22 or newer

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card