go - 运行时:当将结构保存到 json 时,goroutine 堆栈超过 1000000000 字节的限制
问题描述
我已经定义了 Trie 数据结构的 go struct。
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))
解决方案
问题是每个Node
都引用了它的父母,以及它的孩子。因此,当它对子字段进行编码时,对于父字段,它再次对父字段进行编码,对于该父字段,它再次对子字段进行编码,等等。一个简单的解决方案是Parent
在编码时不使用该字段
Parent *Node `json:"-"`
这将阻止循环。
推荐阅读
- python - 如何根据其他 2 列替换 numpy 数组中的值
- c# - C# 将 XML 文件从给定标签解析为对象
- javascript - ImageBackground 在 react native + expo 中不显示本地图像
- php - Laravel 根据来自 Db 的内容中的表达式查找和替换内容
- java - 处理第二次点击卡片视图
- javascript - 如何在 cshtml 中添加电子邮件、沙特手机和国民身份证验证?
- sql - SQL Server 用逗号分隔列中的字符串,并在不使用拆分方法的情况下搜索值,并且检查应该是 AND 而不是 OR
- angularjs - 如何在每个堆叠条形图单元格中设置不同的颜色?
- reactjs - 使用 cra 在反应中排序顺序导入
- javascript - 使用 ajax API 发送 PUT 请求时出现 Cors 错误