首頁  >  文章  >  後端開發  >  在 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刪除