英文:
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 := <- 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论