首页 > 解决方案 > 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”。

非常感谢你的帮助!

标签: gostack-overflow

解决方案


由于父/子指针,您有多个无限循环。每个父母都指向它的孩子,孩子又指向他们的父母。请注意,当反序列化时,指向同一对象的多个指针最终将成为多个单独的对象,这可能不是您想要的。


推荐阅读