go
runtime_error
ai_generated
true
panic:向 nil map 赋值
panic: assignment to entry in nil map
ID: go/nil-map-write
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.
解决方案
-
98% 成功率
m := make(map[string]int) m["k"] = 1
-
98% 成功率
m := map[string]int{"k": 1} -
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 }
无效尝试
常见但无效的做法:
-
90% 失败
The map stays nil; subsequent writes panic again.
-
85% 失败
Does not address the nil map; sync.Map is a different type.
-
80% 失败
Silently drops data; the map still needs initialization.