Go language select statement
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.
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.
Grammar
The syntax of the 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);
}
The following description describes select
syntax of the statement:
Each
case
must be a communication.All
channel
expressions are evaluated.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
case
can be run.Select
will be randomly and fairly selected for execution. The rest will not be carried out. Otherwise:If there is
default
clause, the statement is executed.If there is no
default
clause,select
will block until a communication can run;Go
will not re evaluatechannel
or values.
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")
}
}
The result of the above code execution is:
no communication