英文:
How is this "checking if a channel is closed" working?
问题
var msg = make(chan string)
func checkChannelAndSendMessage() {
select {
case <-msg:
fmt.Print("channel is closed")
default:
msg <- "hey"
}
}
func readMessage() {
for {
fmt.Print(<-msg)
}
}
我有一段代码触发了checkChannelAndSendMessage函数。我不明白这个select语句是如何工作的,它是如何检查通道是否打开,并且只在通道打开时发送消息的。有人可以解释一下吗?
英文:
var msg = make(chan string)
func checkChannelAndSendMessage() {
select {
case <-msg:
fmt.Print("channel is closed")
default:
msg <- "hey"
}
}
func readMessage() {
for {
fmt.Print(<-msg)
}
}
I have a piece of code which triggers checkChannelAndSendMessage function. I don't understand how this select statement is working to check if a channel is open and then sending messages only if channel is open. Someone please explain it.
答案1
得分: 1
default:
情况将在通道打开且没有其他goroutine向该通道发送数据时执行。case <-msg:
情况将在通道关闭(返回通道元素类型的零值)时执行,或者在其他goroutine向该通道发送数据时执行。
这意味着该函数本身并不是绝对可靠的,它可能会在通道实际上是打开的情况下打印"channel is closed"
。
英文:
The default:
case will be executed if the channel is open and no other goroutine is sending data to that channel. The case <-msg:
case will be executed if the channel is closed (returning the zero value of the channel's element type), or it will be executed if some other goroutine is sending data to that channel.
That means that the function by itself is not foolproof, it could very well be used in such a way that it'd print "channel is closed"
even while the channel is actually open.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论