Nil Map Assignment

ID

go.nil_map_assignment

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

reliability, suspicious

Description

Reports an index assignment m[k] = v into a map variable declared with var m map[K]V and never initialised. Writing to a nil map panics at runtime.

Rationale

A var-declared map is nil. Reading from a nil map is safe — it yields the zero value — but writing to one panics with assignment to entry in nil map. The map must be created with make(map[K]V) or a composite literal map[K]V{} before any write.

To stay free of false positives the rule works within a single function and bails out if anything between the declaration and the write could have initialised the map (a m = …​ assignment, a m := …​ short declaration, or an earlier index write). Only the first write into a never-initialised nil map is reported.

var m map[string]int
m["a"] = 1            // FLAW — assignment to entry in nil map

var m map[string]int
m = make(map[string]int)
m["a"] = 1            // OK — initialised before the write

m := map[string]int{}
m["a"] = 1            // OK — composite literal

Remediation

Initialise the map before writing to it: m := make(map[K]V) (or m := map[K]V{}), or change the declaration to var m = make(map[K]V).