Unnecessary Delete Guard
ID |
go.unnecessary_delete_guard |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Go |
Tags |
CWE:1164, code-style, readability |
Description
Reports if _, ok := m[k]; ok { delete(m, k) } — a presence check guarding a delete of the same
key, which can be reduced to an unconditional delete(m, k).
Rationale
The delete builtin is already a no-op when the key is absent (and even when the map is nil), so
guarding it with a presence check adds nothing but nesting and a redundant map lookup. Dropping the
guard makes the intent — "remove this key" — immediate. The check is conservative: it fires only
when the if init is _, ok := m[k], the condition is the bare ok, the body is exactly the
matching delete(m, k), and there is no else.
if _, ok := m[k]; ok { // FLAW — the guard is unnecessary
delete(m, k)
}
delete(m, k) // OK — deleting a missing key is already a no-op