首页  >  文章  >  后端开发  >  在 golang 中使用 Goldmark 附加 ChildNode 会导致堆栈溢出

在 golang 中使用 Goldmark 附加 ChildNode 会导致堆栈溢出

PHPz
PHPz转载
2024-02-08 20:42:11885浏览

在 golang 中使用 Goldmark 附加 ChildNode 会导致堆栈溢出

问题内容

我一直在 go 中使用 goldmark,我是新手,所以我不确定我是否正确地执行了此操作。我一直在阅读文档,但是我对为什么会发生这种情况感到有点困惑。

我已经解析了一个 markdown 文件并使用 ast.walk 来遍历 ast。

我的目标是在列表项下注入子列表。

ast.walk(doc, func(n ast.node, entering bool) (ast.walkstatus, error) {
    if entering {
        if n.kind() == ast.kindlistitem {
            sublist := ast.newlist(0)
            sublistitem := ast.newlistitem(0)
            sublist.appendchild(sublist, sublistitem)

            leaf := ast.newstring([]byte("hello"))
            sublistitem.appendchild(sublistitem, leaf)
            n.appendchild(n, sublist)
        }
    }

    return ast.walkcontinue, nil
})

但是,当我运行这个时,我得到

runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc04f9803c8 stack=[0xc04f980000, 0xc06f980000]
fatal error: stack overflow

我认为这是由于添加新节点并在下一次迭代中访问该节点造成的。但是我不完全确定如何跳过新节点。


正确答案


你是对的,堆栈溢出错误是由新节点的访问引起的。

要解决此问题,您可以记录添加的节点并在 walk 函数中跳过它们。

// for recording the added nodes
added := make(map[*ast.List]bool)

ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
    if entering {
        if n.Kind() == ast.KindList {
            if _, ok := added[n.(*ast.List)]; ok {
                // skip the added node
                return ast.WalkSkipChildren, nil
            }
        }
        if n.Kind() == ast.KindListItem {
            subList := ast.NewList(0)
            subListItem := ast.NewListItem(0)
            subList.AppendChild(subList, subListItem)

            leaf := ast.NewString([]byte("Hello"))
            subListItem.AppendChild(subListItem, leaf)
            n.AppendChild(n, subList)

            // record the added node
            added[subList] = true
        }
    }

    return ast.WalkContinue, nil
})

以上是在 golang 中使用 Goldmark 附加 ChildNode 会导致堆栈溢出的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除