Skip to content

Replace delete-all loops with clear Has Fix

Description

The clear built-in expresses removing every entry from a map without a handwritten loop. Concrete-syntax strictness ensures the fix is offered only when the loop body is exactly the matching delete call, without comments that the rewrite could discard.

Use this rule only when the project targets Go 1.21 or newer.

YAML

yaml
id: use-clear
language: Go
rule:
  pattern:
    context: |-
      for $KEY := range $MAP {
        delete($MAP, $KEY)
      }
    strictness: cst
fix: clear($MAP)

Example

go
func reset(entries map[string]int) {
  for key := range entries {
    delete(entries, key)
  }
}

Diff

go
func reset(entries map[string]int) {
  for key := range entries { 
    delete(entries, key) 
  } 
  clear(entries) 
}

Credits

Inspired by JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust