fallthrough:Go里面switch默認(rèn)相當(dāng)于每個(gè)case最后帶有break,匹配成功后不會(huì)自動(dòng)向下執(zhí)行其他case,而是跳出整個(gè)switch, 但是可以使用fallthrough強(qiáng)制執(zhí)行后面的case代碼。
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è)分支。
上述示例是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
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ò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:汕頭 吐魯番 梅河口 雞西 欽州 蘭州 重慶 銅川
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《go語(yǔ)言中fallthrough的用法說(shuō)明》,本文關(guān)鍵詞 語(yǔ),言中,fallthrough,的,用法,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。