在Go中读取直到通道结束

gre*_*rep 5 idioms go channels

生产者用一些值填充通道并关闭它.在消费者方面,我想将所有值加起来并将循环留在最后.我的解决方案如下:

total := 0
for {
    v, ok := <- ch
    if !ok { break }
    total += v
}
Run Code Online (Sandbox Code Playgroud)

还有更优雅的方式吗?

lnm*_*nmx 10

只要生产者关闭了通道,for/range循环就可以工作.

total := 0

for v := range ch {
    total += v
}
Run Code Online (Sandbox Code Playgroud)

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