无涯教程-Go - select 语句函数

48 阅读1分钟

Go编程语言中 select 语句的语法如下-

select {
   case communication clause  :
      statement(s);      
   case communication clause  :
      statement(s); 
   /* 你可以有任意数量的case语句 */
   default : /* 可选 */
      statement(s);
}

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): //等同于: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

参考链接

www.learnfk.com/go/go-selec…