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

huangapple go评论86阅读模式
英文:

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 &lt;- element
        go send()
    } else {
      close(elements)
    }
}
go send()

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

huangapple
  • 本文由 发表于 2011年9月29日 08:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/7591050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定