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.

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

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂