英文:
What is the issue on my recursive function made in go?
问题
我正在学习使用《Go语言圣经》这本书学习Golang,在第5章第5.3节(多返回值)的练习5.5中,我需要实现一个名为countWordAndImages
的函数,该函数接收来自golang.org/x/net包的html Node,并计算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)
)。
英文:
I am learning Golang with the book "The Go Programming Language", in chapter 5 section 5.3 (Multiple Return Values) exercise 5.5 I have to implement the function countWordAndImages
that receives an html Node from the (golang.org/x/net) package, and counts the number of words and images inside an html file, I implemented the following function, but for any reason I receive 0 values for each words
and images
returned variables.
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
}
I tried to avoid naming the return varibles tuple in the function ((int, int)
).
答案1
得分: 3
使用c.NextSibling
来前进到下一个兄弟节点,而不是n.NextSibling
:
for c := n.FirstChild; c != nil; c = c.NextSibling {
⋮
}
链接:https://go.dev/play/p/cm51yG8Y7Ry
英文:
Use c.NextSibling
to advance to the next sibling, not n.NextSibling
:
for c := n.FirstChild; c != nil; c = c.NextSibling {
⋮
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论