Go —— 選擇語句



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 的 type 必須是通訊通道操作。

  • 當通道操作發生時,將執行 case 之後的語句。case 語句中不需要 break

  • 一個 select 語句可以有一個可選的 default case,它必須出現在 select 的末尾。default case 可用於在沒有 case 為真時執行任務。default case 中不需要 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
go_decision_making.htm
廣告
© . All rights reserved.