Go語言學習筆記五: 條件語句

Go語言學習筆記五: 條件語句

if語句

if 布爾表達式 {
   /* 在布爾表達式爲 true 時執行 */
}

居然沒有括號,和python很像。可是有大括號,與python又不同。python

例子:git

package main

import "fmt"

func main() {
   var a int = 1
   if a < 2 {
       fmt.Printf("a < 2\n" )
   }
   fmt.Printf("a = %d\n", a)
}

if..else語句

if 布爾表達式 {
   /* 在布爾表達式爲 true 時執行 */
} else {
  /* 在布爾表達式爲 false 時執行 */
}

if..else if..else 語句嵌套

if score >= 90 {
    fmt.Println("優秀")
} else if score >= 70 {
    fmt.Println("良好")
} else if score >= 60 {
    fmt.Println("通常")
} else {
    fmt.Println("差")
}

if 語句嵌套

if 布爾表達式 1 {
   /* 在布爾表達式 1 爲 true 時執行 */
   if 布爾表達式 2 {
      /* 在布爾表達式 2 爲 true 時執行 */
   }
}

switch 語句

switch var1 {
    case val1:
        ...
    case val2, val3:
        ...
    default:
        ...
}

Type Switch

switch 語句還能夠被用於 type-switch 來判斷某個 interface 變量中實際存儲的變量類型。github

switch x.(type){
    case type1:
       statement1    
    case type2:
       statement2 
    default: /* 可選 */
       statement3;
}

select語句

select 語句相似於switch語句,可是select會隨機執行一個可運行的case。若是沒有case可運行,它將阻塞,直到有case可運行。golang

這個東西我還真沒有在其餘語言裏面看到過(多是我瞭解的太少)。學習

select {
    case communication clause  :
       statement1;      
    case communication clause  :
       statement2; 
    /* 你能夠定義任意數量的 case */
    default : /* 可選 */
       statement3;
}
  • 每一個case都必須是一個通訊
  • 全部channel表達式都會被求值
  • 全部被髮送的表達式都會被求值
  • 若是任意某個通訊能夠進行,它就執行;其餘被忽略。
  • 若是有多個case均可以運行,Select會隨機公平地選出一個執行。其餘不會執行。
  • 不然:若是有default子句,則執行該語句。若是沒有default字句,select將阻塞,直到某個通訊能夠運行;Go不會從新對channel或值進行求值。

學習這個須要先學習channel。我channel還不會呢,先不深刻看這個了。code

此係列其餘文章地址

https://github.com/zhangqunshi/golang_studyget

相關文章
相關標籤/搜索