英文:
Is it good practice to read a channel as condition for if statement?
问题
我看到了一些关于这个的例子:
type data struct {
request chan string
response chan bool
}
并且像这样使用:
db := &data{make(chan string), make(chan bool)}
if db.request <- "boo"; !<-db.response {
做一些操作...
}
从响应通道中的“轮询”不会阻塞吗?而且,在通道的另一端能够响应之前,if条件有时会被评估吗?这种模式在标准库中是否被使用?
英文:
I've seen a few examples with this:
type data struct {
request chan string
response chan bool
}
and used like this:
db := &data{make(chan string), make(chan bool)}
if db.request<- "boo"; !<-db.response {
do something ...
}
Does "polling" from the response channel not block ? Also won't the if condition be sometimes evaluated before the other end of the channel can respond ? Is this pattern used anywhere in the standard libraries ?
答案1
得分: 3
你没有在进行任何轮询,而且是的,通道接收操作总是可以阻塞的。
<-db.response
是一个普通的接收操作。db.response
通道必须是一个 chan bool
类型,而 !
是逻辑“非”一元运算符。
英文:
You're not polling anything, and yes the channel receive operation can always block.
<-db.response
is a normal receive operation. The db.response
chan must be a chan bool
, and the !
is the logical "not" unary operator.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论