首頁 > 後端開發 > Golang > 主體

我用 go 寫的遞歸函數有什麼問題?

王林
發布: 2024-02-06 10:27:07
轉載
383 人瀏覽過

我用 go 编写的递归函数有什么问题?

問題內容

我正在透過《the go 程式語言》一書學習golang,在第5 章第5.3 節(多個回傳值)練習5.5 中,我必須實作函數countwordandimages,該函數從(golang.org/x/ net) 套件中,併計算html 檔案中的單字和圖像數量,我實作了以下函數,但出於某種原因,我收到每個wordsimages 傳回變數的0 值

func countWordsAndImages(n *html.Node) (words, images int) {
    if n.Type == html.TextNode {
        words += wordCount(n.Data)
    } else if n.Type == html.ElementNode && n.Data == "img" { // if tag is img on element node
        images++
    }
    for c := n.FirstChild; c != nil; c = n.NextSibling {
        tmp_words, tmp_images := countWordsAndImages(c)
        words, images = words+tmp_words, images+tmp_images
    }
    return words, images
}

func wordCount(s string) int {
    n := 0
    scan := bufio.NewScanner(strings.NewReader(s))
    scan.Split(bufio.ScanWords)
    for scan.Scan() {
        n++
    }
    return n
}
登入後複製

我試圖避免在函數中命名回傳變數元組 ((int, int))。


正確答案


使用c.nextsibling 前進到下一個兄弟,而不是n.nextsibling

for c := n.FirstChild; c != nil; c = c.NextSibling {
    ⋮
登入後複製

https://www.php.cn/link/e7364a5abd2a860cf8e33b114369b92b

以上是我用 go 寫的遞歸函數有什麼問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!