结构Json Marshaling导致堆栈溢出

时间:2018-06-18 15:06:59

标签: go stack-overflow

问题

当我在我的代码中使用NewChild()函数时,然后编组"报告"结构到JSON我得到一个Stack Overflow(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"。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

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

相关问题