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