go
runtime_error
ai_generated
true
恐慌:json:无限递归(无效循环)
panic: json: infinite recursion (invalid cycle)
ID: go/encoding-json-marshal-infinite-recursion
80%修复率
81%置信度
0证据数
2025-07-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
结构体存在循环引用,导致json.Marshal无限递归,最终栈溢出。
English
A struct has a circular reference that causes json.Marshal to recurse infinitely, leading to a stack overflow.
解决方案
-
90% 成功率 Implement json.Marshaler to break cycles or use pointer indirection
type Node struct { Value int Next *Node } func (n *Node) MarshalJSON() ([]byte, error) { if n == nil { return json.Marshal(nil) } return json.Marshal(struct{ Value int }{Value: n.Value}) }
无效尝试
常见但无效的做法:
-
Adding a depth counter to break recursion
50% 失败
May still panic if depth exceeded; better to use custom marshaler.