登录
首页 >  Golang >  Go问答

go 编写的递归函数存在哪些问题?

来源:stackoverflow

时间:2024-02-06 21:45:20 289浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《go 编写的递归函数存在哪些问题?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在通过《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://go.dev/play/p/cm51yg8y7ry

今天关于《go 编写的递归函数存在哪些问题?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>