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

推荐答案

使用c.NextSibling前进到下一个同级,而不是n.NextSibling:

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

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

Go相关问答推荐

如何创建两个连接的io.ReadWriteClosers以用于测试目的

Makefile:现有文件上没有这样的文件或目录,不加载环境变量

你能帮我优化一个golang代码关于函数CrossPointTwoRect

理解Golang并发:缓冲通道的意外行为

使用Goldmark在golang中添加ChildNode会导致堆栈溢出

如何解决构建Docker Compose时的权限被拒绝问题

是否可以在调试期间在 VSCode 中预览 github.com/shopspring/decimal 值?

最长连续重复的字符golang

此 Golang 程序中的同步问题

如何使用 Go 代理状态为 OK 的预检请求?

assert: mock: I don't know what to return because the method call was unexpected 在 Go 中编写单元测试时出错

访问传递给可变参数函数的通用 struct 的特定字段

Go:从 ssl 证书中获取 'subject/unstructeredName' 的值

grpc-gateway:重定向与定义不匹配(原始文件)

来自洪流公告的奇怪同行字段

无法访问 Go 模块导入的远程存储库

Go AST:获取所有 struct

Golang 使用 docker 将敏感数据作为参数传递

显示作为服务帐户身份验证的谷歌日历事件 - Golang App

在 go (1.18) 的泛型上实现多态的最佳方法是什么?