【问题标题】:Struct Json Marshaling Causing stack overflowStruct Json Marshaling 导致堆栈溢出
【发布时间】:2018-11-27 11:29:43
【问题描述】:

问题

当我在我的代码中使用 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”。

非常感谢您的帮助!

【问题讨论】:

  • 如果ReportElement有指向子节点和父节点的指针,说明数据结构有循环。

标签: go stack-overflow


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2010-09-11
    • 2015-12-21
    相关资源
    最近更新 更多