fallthrough:Go里面switch默認(rèn)相當(dāng)于每個case最后帶有break,匹配成功后不會自動向下執(zhí)行其他case,而是跳出整個switch, 但是可以使用fallthrough強制執(zhí)行后面的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")
}
輸出結(jié)果:
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常量進(jìn)行分支判斷,看如下變量示例。
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")
}
輸出結(jié)果如下:
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
總結(jié):
switch分支中使用變量進(jìn)行判斷的時,fallthrough正確的分支開始其作用。
補充:【踩坑】golang的fallthrough大坑
加了fallthrough后,會直接運行【緊跟的后一個】case或default語句,不論條件是否滿足都會執(zhí)行,后面的條件并不會再判斷了,?
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- Golang 編譯成DLL文件的操作
- golang調(diào)用c實現(xiàn)的dll接口細(xì)節(jié)分享
- Golang如何調(diào)用windows下的dll動態(tài)庫中的函數(shù)
- go mod 使用私有g(shù)itlab群組的解決方案
- django將圖片保存到mysql數(shù)據(jù)庫并展示在前端頁面的實現(xiàn)
- golang實踐-第三方包為私有庫的配置方案
- 解決go mod私有倉庫拉取的問題