go runtime_error ai_generated true

panic:向 nil map 赋值

panic: assignment to entry in nil map

ID: go/nil-map-write

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-03-06首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.22 active — — —

根因分析

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

English

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

generic

解决方案

  1. 98% 成功率
    m := make(map[string]int)
    m["k"] = 1
  2. 98% 成功率
    m := map[string]int{"k": 1}
  3. 90% 成功率
    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
    }

无效尝试

常见但无效的做法:

  1. 90% 失败

    The map stays nil; subsequent writes panic again.

  2. 85% 失败

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

  3. 80% 失败

    Silently drops data; the map still needs initialization.