duanbi1983
2019-02-05 16:31
浏览 65
已采纳

运行时:将结构保存到json时,goroutine堆栈超过了1000000000字节限制

I've defined a go struct of Trie data structure.

type Node struct {
Val      rune
IsWord   bool
IsRoot   bool
Parent   *Node
Children map[rune]*Node
}
type Trie struct {
Root *Node
}
trie := algorithms.InitTrie()

However, it raises an error

runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
runtime stack:
runtime.throw(0x10e9426, 0xe)
/usr/local/go/src/runtime/panic.go:605 +0x95
runtime.newstack(0x0)
/usr/local/go/src/runtime/stack.go:1050 +0x6e1
runtime.morestack()
/usr/local/go/src/runtime/asm_amd64.s:415 +0x86

When I insert some words and save it into json file.

fmt.Println(json.Marshal(&trie))
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanchifo2866 2019-02-05 17:22
    已采纳

    The problem is that each Node has a reference to it's parent, as well as to it's children. So when it encodes a child, for the parent field, it encodes the parent again, and for that parent, it encodes the child again, etc. A simple solution would be to simply not use the Parent field when encoding

    Parent   *Node `json:"-"`
    

    This will prevent the cycle.

    https://play.golang.org/p/BdVgMNjlZOa

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

相关推荐 更多相似问题