Unnecessary Map Access Guard

ID

go.unnecessary_map_access_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 a presence check guarding a map write whose else branch reproduces the exact result the map’s zero value already provides, so the whole if collapses to the then-branch alone.

Rationale

Accessing a missing map key returns the zero value, which is frequently a perfectly usable starting point: an empty slice for append, 0 for integer arithmetic. When the else branch only rebuilds that same zero-based result, the if _, ok := m[k]; ok guard is pure ceremony — the then-branch works unconditionally. The check is conservative and recognises only three shapes whose else branch is provably equivalent to the zero value: append/composite-literal, += v/= v, and ++/= 1.

if _, ok := m[k]; ok { // FLAW — the zero value already works
    m[k] = append(m[k], v)
} else {
    m[k] = []T{v}
}

m[k] = append(m[k], v) // OK — equivalent, without the guard

Remediation

Delete the if/else and keep the then-branch statement, which already produces the correct result from the zero value.