本文系第八篇Golang語言學習教程
switch是一個條件陳述式,用於將運算式的值與可能匹配的選項列表進行比較,並根據情況執行相應代碼。是替代if else的常用方式。
下面通過講解一個簡單的運算程式來瞭解switch語句
package mainimport "fmt"func eval(a, b int, op string) int { //定義eval函數,輸入三個值 a, b, op 輸出類型為 int var result int switch op { // op 為運算式,將 op 的值與下面 case 比較 case "+": //若 op 值為 + , 則將 result 賦值 a + b 以此類推 result = a + b case "-": result = a - b case "*": result = a * b case "/": result = a / b default: //如果輸入沒有以上匹配的字元,則屬於預設情況,運行預設情況 fmt.Println("unsupported operator:" + op) //輸出不識別 op 值的報錯 } return result}func main(){ fmt.Println( eval(10, 4, "+"), eval(15, 6, "-"), eval(2, 4, "*"), eval(100, 4, "/"), )}
在以上程式中,switch 將 op 的值作為運算式,與case比較。op值若為"+",所以匹配到第一個case,給result賦值後退出case。以此類推
若op輸入的值沒有匹配到,則屬於預設情況,運行預設代碼,本程式輸出報錯。
以上程式執行結果為 :14 9 8 25
多運算式判斷
通過用,逗號隔開,一個case中可以寫多個運算式
func main(){ letter := "i" switch letter { case "a", "o", "e", "i", "u": //用 "," 逗號分隔,多個運算式 fmt.Println(letter, "is in vowel") default: fmt.Println(letter, "is not in vowel") }}
在 case a,e,i,o,u: 這一行中,列舉了所有的母音。只要匹配該項,則將輸出 i is in vowel
無運算式的switch
switch中,運算式是可選的,如果省略運算式,則這個switch語句等同於switch true,每個case都被認定為有效,執行相應的代碼塊。
func main(){ num := 79 switch { //省略運算式 case num >= 0 && num <= 50: fmt.Println("num is greater than 0 and less than 50") case num >= 50 && num <= 100: fmt.Println("num is greater than 50 and less than 100") case num >= 100: fmt.Println("num is greater than 100") }}
在以上程式中,num值為79,省略運算式,則匹配每個case,直至結束。
以上程式輸出輸出: num is greater than 50 and less than 100
Fallthrough語句
在 Go 中,每執行完一個 case 後,會從 switch語句中跳出來,不再做後續 case 的判斷和執行。使用fallthrough語句可以在已經執行完成的 case 之後,把控制權轉移到下一個case 的執行代碼中。
還是上一個程式,但如果將num賦值100,只會匹配到第二個case後跳出,我們加上fallthrough後查看效果。
func main(){ num := 79 switch { //省略運算式 case num >= 0 && num <= 50: fmt.Println("num is greater than 0 and less than 50") case num >= 50 && num <= 100: fmt.Println("num is greater than 50 and less than 100") fallthrough case num >= 100: fmt.Println("num is greater than 100") }}
num := 100,可以配置第二個case,也可以匹配第三個,通過fallthrough,我們成功的同時匹配到了兩個case。
注意:fallthrough語句應該是 case 子句的最後一個語句。不要寫在case語句的中間。
以上為學習Golang switch篇