Read until end of channel in Go

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

Read until end of channel in Go

问题

生产者向通道填充一些值并关闭它。
在消费者端,我想将所有的值相加,并在最后离开循环。我的解决方案如下:

total := 0
for {
    v, ok := <- ch
    if !ok { break }
    total += v
}

有没有更优雅的方法?

英文:

The producer fills up the channel with some values and closes it.
On the consumer side I want to add up all the values and leave the loop at the end. My solution looks like:

total := 0
for {
    v, ok := &lt;- ch
    if !ok { break }
    total += v
}

Is there any more elegant way?

答案1

得分: 12

一个for/range循环将起作用,只要生产者关闭通道。

total := 0

for v := range ch {
    total += v
}

播放:http://play.golang.org/p/cWcA57dnLC

英文:

A for/range loop will work, as long as the producer closes the channel.

total := 0

for v := range ch {
    total += v
}

Play: http://play.golang.org/p/cWcA57dnLC

huangapple
  • 本文由 发表于 2013年10月1日 01:29:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/19100252.html
匿名

发表评论

匿名网友

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

确定