a <- <- b
與a<- (<-b)
相同,因爲<-
運營商與最左邊的chan
可能關聯。
所以select
有一個case
與發送操作(的形式a<- (something)
)。這裏發生的是send語句的右側表達式(要發送的值)首先被計算 - 這是<-b
。但是,這將永遠阻止(因爲沒有人在b
發送任何數據),所以:
fatal error: all goroutines are asleep - deadlock!
相關部分形成Spec: Select statements:
Execution of a "select" statement proceeds in several steps:
For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.
If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.
...
所以,如果default
存在,則select
確實防止阻塞,如果沒有的通信可以在步驟2中繼續,但是您的代碼卡在步驟1中。
只要是完整的,是否會有這將在b
發送的值,那麼<- b
評價不會阻止的goroutine,所以select
的執行將不會停留在步驟2中,和你會看到預期的"select worked as naively expected"
(因爲從a
接收仍然無法因此繼續default
將選擇):
go func() { b <- 1 }()
select {
// ...
}
嘗試它的Go Playground。