go runtime_error ai_generated true

panic: assignment to entry in nil map

ID: go/nil-map-write

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-03-06First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.22 active — — —

Root Cause

A write to a map that was declared but not initialized with make() or a literal.

generic

中文

向只声明未用 make() 或字面量初始化的 map 写入。

Workarounds

  1. 98% success
    m := make(map[string]int)
    m["k"] = 1
  2. 98% success
    m := map[string]int{"k": 1}
  3. 90% success
    func set(m map[string]int, k string, v int) map[string]int {
        if m == nil { m = make(map[string]int) }
        m[k] = v
        return m
    }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The map stays nil; subsequent writes panic again.

  2. 85% fail

    Does not address the nil map; sync.Map is a different type.

  3. 80% fail

    Silently drops data; the map still needs initialization.