Skip to content

Find map copy loops that may use maps.Copy

Description

Since Go 1.21, maps.Copy(dst, src) clearly expresses a shallow copy that overwrites matching destination keys. This rule finds loops whose body is exactly dst[k] = v and keeps the destination to a plain identifier.

No automatic fix is offered because ast-grep does not resolve Go types. Assignment permits cases such as copying map[string]string into map[any]any, while maps.Copy requires compatible key and value types. Verify the types before converting the loop, and add import "maps" when needed.

YAML

yaml
id: use-maps-copy
language: Go
severity: hint
message: Consider maps.Copy after verifying compatible map types.
rule:
  pattern:
    context: |
      for $KEY, $VALUE := range $SOURCE {
        $DESTINATION[$KEY] = $VALUE
      }
    selector: for_statement
    strictness: cst
constraints:
  DESTINATION:
    kind: identifier

Example

go
func merge(dst, src map[string]int) {
  for key, value := range src {
    dst[key] = value
  }
}

Credits

Based on JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust