go runtime_error ai_generated true

恐慌:json:为类型main.MyType调用MarshalJSON时使用了不可寻址的值

panic: json: calling MarshalJSON for type main.MyType with non-addressable value

ID: go/encoding-json-marshal-non-addressable-value

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

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

尝试编组一个不可寻址的值,例如映射键,无法调用其方法。

English

Attempting to marshal a value that is not addressable, such as a map key, which cannot have its method called.

generic

解决方案

  1. 90% 成功率 Ensure MarshalJSON has pointer receiver and pass pointer
    func (m *MyType) MarshalJSON() ([]byte, error) { ... }
    // Always pass pointer
    json.Marshal(&myValue)

无效尝试

常见但无效的做法:

  1. Using reflect to make it addressable 70% 失败

    Complex and may panic; better to use pointer receiver.