我用书"The Go Programming Language"学习Golang,在第5章第5.3节(多个返回值)练习5.5中,我必须实现函数countWordAndImages
,该函数从(golang.org/x/net)包接收html node ,并计算html文件中的单词和图像的数量,我实现了以下函数,但无论出于什么原因,我都会 for each words
和images
返回的变量接收0 values.
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)
)中命名返回变量元组.