Go - Select 语句
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 语句中不需要中断。
select语句可以有一个可选的默认情况,它必须出现在 select 的末尾。当所有情况都不成立时,可以使用默认情况来执行任务。默认情况下不需要中断。
例子
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
go_decision_making.htm