fallthrough:Go里面switch默認相當於每個case最后帶有break,匹配成功后不會自動向下執行其他case,而是跳出整個switch, 但是可以使用fallthrough強制執行后面的case代碼。
示例程序1:
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") fallthrough case false: fmt.Println("The integer was <= 8") default: fmt.Println("default case") }
輸出結果:
The integer was <= 5
The integer was <= 6
The integer was <= 7
The integer was <= 8
問題:是否在switch最后一個分支使用fallthrough???
有錯誤提示,顯示:cannot fallthrough final case in switch
fallthrough不能用在switch的最后一個分支。
示例程序2:
上述示例是true、false常量進行分支判斷,看如下變量示例。
s := "abcd" switch s[1] { case 'a': fmt.Println("The integer was <= 4") fallthrough case 'b': fmt.Println("The integer was <= 5") fallthrough case 'c': fmt.Println("The integer was <= 6") default: fmt.Println("default case") }
輸出結果如下:
The integer was <= 5
The integer was <= 6
更改為:
s := "abcd" switch s[3] { case 'a': fmt.Println("The integer was <= 4") fallthrough case 'b': fmt.Println("The integer was <= 5") fallthrough case 'c': fmt.Println("The integer was <= 6") default: fmt.Println("default case") }
輸出:
default case
總結:switch分支中使用變量進行判斷的時,fallthrough正確的分支開始其作用。