
我正在通过《the go 编程语言》一书学习 golang,在第 5 章第 5.3 节(多个返回值)练习 5.5 中,我必须实现函数 countwordandimages,该函数从 (golang.org/x/ net) 包中,并计算 html 文件中的单词和图像数量,我实现了以下函数,但出于某种原因,我收到每个 words 和 images 返回变量的 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号