英文:
How do you iterate over all values produced by a function?
问题
我是新手,发现自己写了一些类似这样的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)
}
但目前,我想知道是否有更简洁的方法来迭代这些函数的输出。特别是,是否有一种好的方法来消除for
语句的初始化语句和后置语句中的重复代码?
英文:
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?
答案1
得分: 2
我不认为有什么比你要找的更简洁的了。写法的惯用方式是:
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)
}
答案2
得分: 0
这是一种从这样的方法创建通道的方式:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论