golang學習(3):go的流程和函式
一、流程控制
- if 和其他語言沒什麼區別,只是判斷語句不加括號,比如:
if integer := 5; integer == 3 { fmt.Println("The integer is equal to 3") } else if integer < 3 { fmt.Println("The integer is less than 3") } else { fmt.Println("The integer is greater than 3") }
- goto 這個就神奇了,用goto跳轉到必須在當前函式內定義的標籤,上程式碼比較好:
i := 5 here: i++ fmt.Println(i) if i < 10 { goto here } else { goto there } fmt.Printf("沒有到這裡") there: fmt.Printf("直接到這裡") 輸出結果:6 7 8 9 10 直接到這裡
很容易解釋,goto就是把改變了程式的執行順序,直接跳到標籤的位置開始執行,比如示例中there 和her e就是兩個標籤。特別注意的是標籤名是大小寫 敏感的。
-
forgo中的for用法很多,基本你能想到的,試試都可以行的通,主要介紹兩種:
第一種是最基本的用法,三個條件語句,當然你也可以定義一個什麼的
for a := 5;a<10;a++{ fmt.Println(a) }
第二種for配合range可以用於讀取slice和map的資料
for k,v:=range map { fmt.Println("map's key:",k) fmt.Println("map's val:",v) }
另外還有break 和continue 關鍵字,break跳出迴圈,continue跳出本次迴圈。
- switch 示例說明:
i := 5 switch i { case 1: println(1) case 5: println(5) case 3: println(1) } //輸出5 ,僅執行了第二個case switch i { case 1: println(1) case 5: println(5) fallthrough case 3: println(3) fallthrough case 4: println(4) case 6: println(6) } //輸出5 3 4
連個示例的關鍵在於fallthrough 不同,有fallthrough 的會強制執行他的下一個case,沒有則不會
二、函式
待續