go - Struct Json Marshaling 导致堆栈溢出
问题描述
问题
当我在我的代码中使用 NewChild() 函数然后将“报告”结构编组为 JSON 时,我得到一个堆栈溢出(goroutine 堆栈超过 1000000000 字节限制)
经过研究,我发现它应该做一些无限递归的事情,但我不知道为什么我的代码应该有这个。
代码
type Report struct{
TestSuites []ReportElement
Tests int
Success int
Failed int
Root *ReportElement
CurrentElement *ReportElement `json:"-"`
}
type ReportElement struct{
Success bool
Time bool
LogStorage []string
Childs []ReportElement
Parent *ReportElement
}
func (r *Report) NewChild(){
newElem := ReportElement{}
newElem.Parent = r.CurrentElement
newElem.Childs = make([]ReportElement,0)
newChilds := append(r.CurrentElement.Childs,newElem)
r.CurrentElement.Childs = newChilds
r.CurrentElement = &newElem
}
func TestReporterStackOverflow(t *testing.T) {
report := NewReport()
report.NewChild()
jsonReport,err := json.MarshalIndent(report,""," ")
if err != nil{
t.Fatal(err)
}
t.Log(jsonReport)
}
想法
实际上我不确定它是否必须对我的代码做些什么,因为堆栈跟踪会导致“/usr/local/go/src/encoding/json/encode.go”。
非常感谢你的帮助!
解决方案
由于父/子指针,您有多个无限循环。每个父母都指向它的孩子,孩子又指向他们的父母。请注意,当反序列化时,指向同一对象的多个指针最终将成为多个单独的对象,这可能不是您想要的。
推荐阅读
- swift - 如何从 LocalizedStringKey 获取字符串值?
- android - 当我尝试在 Android Studio 中插入新的矢量资源时,“无显示”
- maven - maven-assembly-plugin:排除文件
- python - 使用 Docker 创建 AWS Lambda 层
- vue2leaflet - ESLint:“'L'未定义”在初始化时使用单个文件组件
- react-native - react-navigation 如何知道之前的路线
- r - 合并多个 data.frames [r]
- solidity - 错误:返回错误:处理事务时出现 VM 异常:还原
- javascript - Angular-Material,如何更改所选垫子选项的颜色
- apache-camel - 如何使用 Apache Camel 获取网页 HTML