目录

select statement

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语句。 每个案例后跟要与之比较的值和冒号。

  • 案例的type必须是通信渠道操作。

  • 当通道操作发生时,将执行该情况之后的语句。 案例陈述中不需要break

  • select语句可以有一个可选的default大小写,它必须出现在select的末尾。 当没有任何情况为真时,默认情况可用于执行任务。 默认情况下不需要break

例子 (Example)

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
↑回到顶部↑
WIKI教程 @2018