Skip to content

Remove redundant range-variable copies Has Fix

Description

Since Go 1.22, variables declared by a range clause are recreated for each iteration. A direct item := item copy is therefore unnecessary, even when a closure captures item or code takes its address.

This rule deliberately matches only variables declared with := in an enclosing range loop. Use it only when the module targets Go 1.22 or newer.

YAML

yaml
id: loopvar-capture
language: Go
rule:
  all:
    - pattern:
        context: func f() { $VAR := $VAR }
        selector: short_var_declaration
    - inside:
        kind: for_statement
        has:
          any:
            - pattern:
                context: for $VAR := range $RANGE {}
                selector: range_clause
                strictness: cst
            - pattern:
                context: for $VAR, $_ := range $RANGE {}
                selector: range_clause
                strictness: cst
            - pattern:
                context: for $_, $VAR := range $RANGE {}
                selector: range_clause
                strictness: cst
        stopBy: end
fix: ""

Example

go
func processAll(items []Item) {
	for _, item := range items {
		item := item
		go process(item)
	}
}

Diff

go
func processAll(items []Item) {
	for _, item := range items {
		item := item 
		go process(item)
	}
}

Credits

Based on JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust