Go 中的 switch fallthrough
阿新 • • 發佈:2021-08-19
參考連結:https://studygolang.com/articles/13389
switch sExpr { case expr1: some instructions case expr2: some other instructions case expr3: some other instructions default: other code }
sExpr和expr1、expr2、expr3的型別必須一致。Go的switch非常靈活,表示式不必是常量或整數,執行的過程從上至下,直到找到匹配項;
而如果switch沒有表示式,它會匹配true。 Go裡面switch預設相當於每個case最後帶有break,匹配成功後不會自動向下執行其他case,而是跳出整個switch, 但是可以使用fallthrough強制執行 後面的case程式碼。
測試用例:
package main import "fmt" func main() { switch { case false: fmt.Println("The integer was <= 4") fallthrough case true: fmt.Println("The integer was <= 5") fallthrough case false: fmt.Println("The integer was <= 6") fallthrough case true: fmt.Println("The integer was <= 7") case false: fmt.Println("The integer was <= 8") fallthrough default: fmt.Println("default case") } }
執行結果:
The integer was <= 5 The integer was <= 6 The integer was <= 7