go - 为什么在go routine中关闭channel会导致receiving channel收到值?

标签 go

我有一个 go 例程,它会定期轮询每个时间间隔并执行操作。它还检查完成 channel ,作为结束信号,以停止轮询。

  go func(){
       for {
          select{
              case <-myticker.C:
                 do_something()
              case <-done:
                 fmt.Println("I am done")
                 return
         } 
       }

    }

我意识到如果我关闭 channel ,它也会运行,就好像值被传递给 done channel 一样,它打印出“我完成了”为什么会这样?

最佳答案

来自规范:

A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received.

参见 https://golang.org/ref/spec#Receive_operator .

关于go - 为什么在go routine中关闭channel会导致receiving channel收到值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143280/

相关文章:

mongodb - 使用 mgo 更新插入到分片 MongoDB 错误 "full shard key must be in update object for collection:..."

rest - HTTP请求被其他HTTP请求篡改,用golang和标准库

go - 如何在 2d 游戏中处理全屏?

json - 如何从JSON解析值。我正在尝试列出单个值,例如python中的字典

Golang 模块使用

go - 如何通过http实现google的protocol buffers

arrays - Go代码为更新的 slice 报告了错误的基础数组?

go - 如何将 HashiCorp 配置语言转换为 JSON?

go - 在 git2go 中将当前分支与上游(或任何其他引用)合并

go - 使用 Openshift/Client-go 进行 Openshift API 查询