在 if 语句中,将一个通道作为条件进行读取是一个好的实践吗?

huangapple go评论82阅读模式
英文:

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 := &amp;data{make(chan string), make(chan bool)}
if db.request&lt;- &quot;boo&quot;; !&lt;-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.

&lt;-db.response is a normal receive operation. The db.response chan must be a chan bool, and the ! is the logical "not" unary operator.

huangapple
  • 本文由 发表于 2015年8月6日 21:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/31857183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定