go switch的用法
最近一直在寫go, switch說實話用的不算多。但是今天用了下發現go的switch可真不太一樣啊。
1、switch語句對case表示式的結果型別有如下要求:
要求case表示式的結果能轉換為switch表示式結果的型別
並且如果switch或case表示式的是無型別的常量時,會被自動轉換為此種常量的預設型別的值。比如整數1的預設型別是int, 浮點數3.14的預設型別是float64
func main() { func main() { value1 := [...]int8{0, 1, 2, 3, 4, 5, 6} switch 1 + 3 { case value1[0], value1[1]: fmt.Println("0 or 1") case value1[2], value1[3]: fmt.Println("2 or 3") case value1[4], value1[5], value1[6]: fmt.Println("4 or 5 or 6") } } }
switch 表示式的結果是int型別,case表示式的結果是int8型別,而int8不能轉換為int型別,所以上述會報錯誤
./main.go:10:1: invalid case value1[0] in switch on 1 + 3 (mismatched types int8 and int)
包含多個表示式的 case
package main import ( "fmt" ) func main() { letter := "i" switch letter { case "a", "e", "i", "o", "u": //multiple expressions in case fmt.Println("vowel") default: fmt.Println("not a vowel") } }
上面的程式檢測 letter 是否是母音。case "a", "e", "i", "o", "u": 這一行匹配所有的母音。程式的輸出為:vowel。
沒有表示式的 switch
switch 中的表示式是可選的,可以省略。如果省略表示式,則相當於 switch true,這種情況下會將每一個 case 的表示式的求值結果與 true 做比較,如果相等,則執行相應的程式碼。
package main import ( "fmt" ) func main() { num := 75 switch { // expression is omitted case num >= 0 && num <= 50: fmt.Println("num is greater than 0 and less than 50") case num >= 51 && num <= 100: fmt.Println("num is greater than 51 and less than 100") case num >= 101: fmt.Println("num is greater than 100") } }
在上面的程式中,switch 後面沒有表示式因此被認為是 switch true 並對每一個 case 表示式的求值結果與 true 做比較。case num >= 51 && num <= 100:的求值結果為 true,因此程式輸出:num is greater than 51 and less than 100。這種型別的 switch 語句可以替代多重 if else 子句。
fallthrough
在 Go 中執行完一個 case 之後會立即退出 switch 語句。fallthrough語句用於標明執行完當前 case 語句之後按順序執行下一個case 語句。 讓我們寫一個程式來了解 fallthrough。下面的程式檢測 number 是否小於 50,100 或 200。例如,如果我們輸入75,程式將列印 75 小於 100 和 200,這是通過 fallthrough 語句實現的。
這裡要注意:fallthrough強制執行後面的case程式碼,fallthrough不會判斷下一條case的expr結果是否為true。
package main import ( "fmt" ) func number() int { num := 15 * 5 return num } func main() { switch num := number(); { //num is not a constant case num < 50: fmt.Printf("%d is lesser than 50\n", num) fallthrough case num < 100: fmt.Printf("%d is lesser than 100\n", num) fallthrough case num < 200: fmt.Printf("%d is lesser than 200", num) } }
switch 與 case 中的表示式不必是常量,他們也可以在執行時被求值。在上面的程式中 num 初始化為函式 number() 的返回值。程式首先對 switch 中的表示式求值,然後依次對每一個case 中的表示式求值並與 true 做匹配。匹配到 case num < 100: 時結果是 true,因此程式列印:75 is lesser than 100,接著程式遇到 fallthrough 語句,因此繼續對下一個 case 中的表示式求值並與 true 做匹配,結果仍然是 true,因此列印:75 is lesser than 200。最後的輸出如下:
75 is lesser than 100 75 is lesser than 200
fallthrough
必須是case
語句塊中的最後一條語句。如果它出現在語句塊的中間,編譯器將會報錯:fallthrough statement out of place
。