Skip to content

Prefer slices.Reverse Has Fix

Description

slices.Reverse clearly expresses an in-place reversal and avoids hand-written index arithmetic. The rule uses CST strictness and identifier constraints so it fixes only the exact two-index swap loop shown below.

This helper requires Go 1.21 or newer. The fix assumes the standard-library slices package is available under its usual name; add the import if needed.

YAML

yaml
id: slices-reverse
language: Go
rule:
  pattern:
    context: |
      for $I, $J := 0, len($SLICE)-1; $I < $J; $I, $J = $I+1, $J-1 {
        $SLICE[$I], $SLICE[$J] = $SLICE[$J], $SLICE[$I]
      }
    selector: for_statement
    strictness: cst
constraints:
  I:
    kind: identifier
  J:
    kind: identifier
  SLICE:
    kind: identifier
fix: slices.Reverse($SLICE)

Example

go
import "slices"

func reverse(items []string) {
	for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
		items[i], items[j] = items[j], items[i]
	}
}

Diff

go
import "slices"

func reverse(items []string) {
	for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 { 
		items[i], items[j] = items[j], items[i] 
	} 
	slices.Reverse(items) 
}

Credits

Based on JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust