我爱占星网 我爱占星网
首页
编程
java
php
前端
首页 编程 java php 前端

读到Go中的频道末尾

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?

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

近期文章

  • mgo中的Golang Bson排序参数
  • 去安装总是使用GOROOT / bin而不是GOPATH
  • Golang-在结构内部使用chan slice
  • 未导出结构中的已导出字段
  • 如何检测两个Golang net.IPNet对象是否相交?
  • 我可以在套件中运行一个测试吗?
  • 为什么Go程序需要运行时支持
  • Golang地图,每个值有多个键
  • 如何在Golang中使用gin-gonic服务器编写流API? 尝试c.Stream没有工作
  • 如何测试并发和锁定golang?
  • 如何在Go中获取变量的内存大小?
  • AppEngine / Go:通过SDK使用新版本的Go
  • 将VueJS与Go后端一起使用
  • Golang if / else无法编译
  • 高朗语中的瑞典语字符
  • 是否需要同步?
  • Go 1.6中的供应商
  • 在Go中使用编码/二进制进行字节尾数转换
  • 为什么在“ if”语句中使用语句?
  • Go等同于Python的crypt.crypt?

Copyright ©2022 我爱占星 All Rights Reserved.

浙ICP备2022030071号-1

部分图文来自网络,如有侵犯您的版权,请告诉我们删除

友情链接:代码精华