如何迭代函数产生的所有值?
我是新手,我发现自己编写了一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为没有什么比你正在寻找的更干净的东西了。惯用的写法是:
I don't think there's anything quite as clean as what you're looking for. The idiomatic way to write it is:
以下是通过此类方法创建通道的方法:
Here's a way to create a channel from such a method: