如何迭代函数产生的所有值?

发布于 2024-12-07 06:17:16 字数 520 浏览 1 评论 0原文

我是新手,我发现自己编写了一些 for 循环,如下所示:

for element, err := producer.Produce(); err == nil; element, err = producer.Produce() {
    process(element)
}

其中 Producer.Produce() 是一个类似于 reader 的函数。 ReadString('\n')fmt.Fscan(Reader, &token)。我很想写,

for element := range elements {
    process(element)
}

但现在,我很高兴知道是否有一种更干净的方法来迭代 go 中此类函数的输出。特别是,是否有一种好方法可以消除 init 语句和 for 语句的 post 语句中这种烦人的重复?

I am new to go, and I have found myself writing a few for loops which look like this:

for element, err := producer.Produce(); err == nil; element, err = producer.Produce() {
    process(element)
}

where producer.Produce() is a function like reader.ReadString('\n') or fmt.Fscan(Reader, &token). I would much rather like to write

for element := range elements {
    process(element)
}

but for now, I would be satisfied to know if there is a cleaner way to iterate over the output of these kinds of functions in go. In particular, is there a nice way to get rid of this annoying duplication in the init statement and the post statement of the for statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

汹涌人海 2024-12-14 06:17:16

我认为没有什么比你正在寻找的更干净的东西了。惯用的写法是:

for {
    element, err := producer.Produce()
    if err != nil {
        break
    }
    process(element)
}

I don't think there's anything quite as clean as what you're looking for. The idiomatic way to write it is:

for {
    element, err := producer.Produce()
    if err != nil {
        break
    }
    process(element)
}
小女人ら 2024-12-14 06:17:16

以下是通过此类方法创建通道的方法:

elements := make(chan elementType)

val send func()
send = func() {
    if element, err := producer.Produce(); err == nil {
        elements <- element
        go send()
    } else {
      close(elements)
    }
}
go send()

for element := range elements {
    process(element)
}

Here's a way to create a channel from such a method:

elements := make(chan elementType)

val send func()
send = func() {
    if element, err := producer.Produce(); err == nil {
        elements <- element
        go send()
    } else {
      close(elements)
    }
}
go send()

for element := range elements {
    process(element)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文