Go 语言条件语句
到目前为止,我们看到的 Go 程序都是从 main() 函数开始执行,然后按顺序执行该函数体中的代码。但我们经常会需要只有在满足一些特定情况时才执行某些代码,也就是说在代码里进行条件判断。针对这种需求,Go 提供了下面这些条件结构和分支结构:
select 结构
Go 编程语言中 select 语句的语法如下:
select {case communication clause :statement(s);case communication clause :statement(s);/* 你可以定义任意数量的 case */default : /* 可选 */statement(s);}
select 语句中,每个 case 都是一个channel,所有 channel 表达式都会被求值。如果任意某个channel可以运行,则其他channel将会被忽略。
如果有多个 channel 都可以运行,Select 会随机公平地选出一个执行。其他channel将不会执行。如果所有channel都无法运行,并且有 default 子句的情况下会执行该语句。如果没有 default 子句,select 将阻塞,直到某个channel可以运行。
示例:
package mainimport "fmt"func main() {var c1, c2, c3 chan intvar i1, i2 intselect {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 := <-c3if ok {fmt.Printf("received ", i3, " from c3\n")} else {fmt.Printf("c3 is closed\n")}default:fmt.Printf("no communication\n")}}
以上代码执行结果为:
no communication