Go编程语言中select
语句的语法如下:
select {
case communication clause :
statement(s);
case communication clause :
statement(s);
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
以下规则适用于select
语句:
- 在
select
语句中可以有任意数量的case
语句。每个case
语句后面都跟要比较的值和冒号。 case
语句中的类型必须是通信通道操作的。- 当发生通道操作时,将执行该
case
语句之后的语句。 在case
语句中可不需要break
语句。 select
语句可以有一个可选的default
语句,它必须出现在select
语句的结尾。default
语句可用于在没有任何case
语句为真时执行任务。在default
语句不需要break
语句。
示例
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