运行时:goroutine堆栈超过1000000000字节的限制,将结构保存到json时[关闭]

问题描述 投票:-4回答:1

我已经定义了Trie数据结构的go结构。

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

但是,会引发错误

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

当我插入一些单词并将其保存到json文件中时。

fmt.Println(json.Marshal(&trie))
go
1个回答
2
投票

问题在于,每个Node都有对其父项以及其子项的引用。因此,当对子项进行编码时,对于父项字段,它将再次对父项进行编码,对于该父项,它将对子项进行再次编码,依此类推。一种简单的解决方案是在编码时不使用Parent字段

Parent   *Node `json:"-"`

这将防止循环。

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

© www.soinside.com 2019 - 2024. All rights reserved.