I am learning golang through the book "the go Programming Language", in Chapter 5, Section 5.3 (Multiple Return Values) In Exercise 5.5, I have to implement the function countwordandimages
, which is from the (golang.org/x/net) package, and count the number of words and images in the html file, I implemented the following function, but I get an error For some reason, I'm receiving a 0 value for each
words and
images return variable.
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)) in the function.
c.nextsibling to advance to the next sibling instead of
n.nextsibling:
for c := n.FirstChild; c != nil; c = c.NextSibling { ⋮
//m.sbmmt.com/link/e7364a5abd2a860cf8e33b114369b92b
The above is the detailed content of What's wrong with my recursive function written in go?. For more information, please follow other related articles on the PHP Chinese website!