Skip to content

Find loops that can range over an integer

Description

Go 1.22 can range directly over an integer, producing values from zero through n-1. This rule finds the equivalent zero-based loop with a unit increment and an identifier, integer literal, or len bound.

No automatic fix is offered because the traditional loop reevaluates its bound on every iteration, while a range expression evaluates it once. The loop body can also modify the counter. Use this suggestion only when the project targets Go 1.22 or newer and both the bound and counter remain stable.

YAML

yaml
id: use-range-over-int
language: Go
severity: hint
message: Consider ranging over the integer after verifying the bound and counter stay stable.
rule:
  pattern:
    context: |-
      for $INDEX := 0; $INDEX < $BOUND; $INDEX++ {
        $$$BODY
      }
    strictness: ast
constraints:
  BOUND:
    any:
      - kind: int_literal
      - kind: identifier
      - pattern: len($COLLECTION)

Example

go
func visit(items []string) {
  for i := 0; i < len(items); i++ {
    process(items[i])
  }
}

Credits

Inspired by JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust