【问题标题】:Read until end of channel in Go在 Go 中阅读直到频道结束
【发布时间】:2013-10-06 16:08:13
【问题描述】:

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

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

还有更优雅的方式吗?

【问题讨论】:

    标签: go idioms channels


    【解决方案1】:

    只要生产者关闭通道,for/range 循环就会起作用。

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

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

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2015-06-03
      • 2010-12-29
      • 2014-04-20
      • 2020-09-22
      相关资源
      最近更新 更多