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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序