这个 select 语句是如何执行的?

How this select statement executes?


incoming := make(chan int)
done := make(chan struct{})

...
close(done)
...

select {
    case incoming <- order:
        // logic
    case <-done:
        return 
    }

假设您在 select 语句之前关闭了已完成的通道:

1.The 个案 <-完成将 selected。

2.Is 这是因为当 close(done) 执行时,done 通道将处于一种状态,在该状态下 select 语句将认为“case <-done”与书写案例“incoming <- order”?

select 语句阻塞,直到其 cases 中的一个或多个 communication operations 可以 继续 。一旦可以进行一个或多个通信操作,select随机 选择其中一个。

在关闭的 channel 上的 receive 操作可以立即 proceed


Select Statement:

Execution of a "select" statement proceeds in several steps:

  1. 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.
  2. 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.
  3. Unless the selected case is the default case, the respective communication operation is executed.
  4. If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned.
  5. The statement list of the selected case is executed.

Receive operator:

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.