我的递归函数在Go语言中有什么问题?

huangapple go评论71阅读模式
英文:

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文件中的单词和图片数量。我实现了以下函数,但是无论出于什么原因,我都会收到每个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))。

英文:

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 {
    ⋮

https://go.dev/play/p/cm51yG8Y7Ry

huangapple
  • 本文由 发表于 2023年1月19日 09:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75166854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定