Home > Backend Development > Golang > What's wrong with my recursive function written in go?

What's wrong with my recursive function written in go?

王林
Release: 2024-02-06 10:27:07
forward
412 people have browsed it

我用 go 编写的递归函数有什么问题?

Question content

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
}
Copy after login

I'm trying to avoid naming the return variable tuple (

(int, int)) in the function.


Correct answer


Use

c.nextsibling to advance to the next sibling instead of n.nextsibling:

for c := n.FirstChild; c != nil; c = c.NextSibling {
    ⋮
Copy after login

https://www.php.cn/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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template