douzhaobo6488
2018-06-18 15:06
浏览 70
已采纳

Struct Json封送处理导致堆栈溢出

Problem

When I use the NewChild() function in my code and than afterwards marshal the "Report" Struct to JSON I get a Stack Overflow (goroutine stack exceeds 1000000000-byte limit)

After researching I found out that it should have to do something with infinite recursion, but I don't have a clue why my code should have that.

Code

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)
}

Ideas

Actually I am not sure if it has to do something with my code as the stacktrace leads to "/usr/local/go/src/encoding/json/encode.go".

Thanks a lot for your help!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanping6698 2018-06-18 15:12
    已采纳

    You have multiple infinite loops due to the parent/child pointers. Each parent points to its children, which point back to their parent. Note that when deserialized, multiple pointers to the same object will end up being multiple separate objects, which likely is not what you want.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题