Go language select statement
Go language conditional statements
select Go is a control structure in a similar statement for the switch to communicate. Each case must be a communication operation, either sending or receiving.
select a random case execution can run. If there is no case to run, it will be blocked until the case can be run. A default clause should always be running.
grammar
Go programming language select statement syntax is as follows:
select { case communication clause : statement(s); case communication clause : statement(s); /* 你可以定义任意数量的 case */ default : /* 可选 */ statement(s); }
The following describes the syntax of the select statement:
- Each case must be a communication
- All channel expression will be evaluated
- All expressions will be sent to be evaluated
- If a communication may be any, it performs; others are ignored.
- If more than one case can run, Select will randomly select a fair execution. Other not be executed.
otherwise:- If there is default clause, the statement is executed.
- If there is no default clause, select the block until a communication may run; Go to channel or not re-evaluated value.
Examples
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 above code is executed as a result of:
no communication