go - 我如何遍历解码器?

标签 go

我有 Python 背景,所以倾向于从迭代器的角度来思考。在我看来,Go 中的 range 关键字旨在让我们以几乎相同的方式思考,所以我想在 Go 中做一些语义上等同于这段 Python 代码的事情:

for obj in json_decoder:
    # business logic

这是 Go 中的激励案例;考虑以下功能:

func (c *GorpController) Create(dec *json.Decoder) {
    // business logic
}

我希望能够将其实现为:

for someValue := range dec {
    // business logic
}

是否有某种方法可以将 rangeDecoder 接口(interface)一起使用?将它包装在不同接口(interface)中的函数将是理想的,并且惯用模式是可以接受的。

谢谢!

最佳答案

不幸的是,您只能将 range 与“数组、 slice 、字符串或映射,或从 channel 读取”一起使用(参见 effective go)

为了在解码时迭代结构,文档建议这样做:

dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
    var m Message
    if err := dec.Decode(&m); err == io.EOF {
        break
    } else if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s: %s\n", m.Name, m.Text)
}

(直接取自 official doc example )

关于go - 我如何遍历解码器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638113/

相关文章:

html - Hugo 不显示子目录 [File.Dir] 中的页面

arrays - 如何解决函数中的 Go 数组大小

unit-testing - 如何在 Golang 的单元测试中测试 net.Conn?

go - 测试并发映射读取和映射写入

pointers - Go和C++的指针区别,gc后指针会变吗?

go - 如何在完成一个 goroutine 后完成所有 goroutine

curl - 来自 cURL 和 Golang POST 的不同响应 - 不明白为什么

http - Golang的 "net/http"中客户端HTTP请求和服务端HTTP请求有什么区别

unit-testing - golang 中的单元测试

macos - GOPATH 没有被自动设置?