select
is a control structure in
Go
, similar to the one used for communication
switch
statement. Each
case
must be a communication operation, either sending or receiving.
The syntax of the The following description describes Each All All expressions sent will be evaluated If any communication can be performed, it is executed and the others are ignored. If there are more than one If there is If there is no The result of the above code execution is:
select
randomly execute a runnable
case
. If not,
case
runnable, it will block until there is
case
can be run. A default clause should always run. 2.22.1. Grammar #
select
statement in the
Go
programming language is as follows:select {
case communication clause :
statement(s);
case communication clause :
statement(s);
/* You can define any number of cases */
default : /* optional */
statement(s);
}
select
syntax of the statement:
case
must be a communication.
channel
expressions are evaluated.
case
can be run.
Select
will be randomly and fairly selected for execution. The rest will not be carried out. Otherwise:
default
clause, the statement is executed.
default
clause,
select
will block until a communication can run;
Go
will not re evaluate
channel
or values. 2.22.2. Example #
select
statement application demonstration:Example #
package main
import "fmt"
func main() {
var c1, c2, c3 chan int
var i1, i2 int
select {
case i1 = <-c1:
fmt.Printf("received ", i1, " from c1\\n")
case c2 <- i2:
fmt.Printf("sent ", i2, " to c2\\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
fmt.Printf("received ", i3, " from c3\\n")
} else {
fmt.Printf("c3 is closed\\n")
}
default:
fmt.Printf("no communication\\n")
}
}
no communication