What is the issue on my recursive function made in go?

62 views Asked by At

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

There are 1 answers

0
Zombo On BEST ANSWER

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