很多的教程在說明golang的switch時,都會特别指明,switch語句不會自動向下貫穿, 是以不必在每一個case子句的末尾都添加一個break語句,有些書本說明, 需要向下貫穿的時候, 顯示調用fallthrough語句.
對于有些人來說, 對于這句話的了解是: 當case語句比對後, 顯示調用fallthrough語句, 那麼就會接着判斷下一個case條件. 我之前就是這麼了解的, 有些書也是這麼了解, 并且這麼舉例的. 網上很多的教程, 也是錯誤的.
《學習go語言》的p12:
它不會比對失敗後自動向下嘗試, 但是可以使用fallthrough 使其這樣做。沒有fallthrough:
switch i {
case 0: // 空的case 體
case 1:
f() // 當i == 0 時,f 不會被調用!
}
而這樣:
switch i {
case 0: fallthrough
case 1:
f() // 當i == 0 時,f 會被調用!
}
事實上, 這樣的了解是錯誤的。
《go web程式設計》的p56:
在第5行中,我們把很多值聚合在了一個 case 裡面,同時,Go裡面 switch 預設相當于每個 case 最後帶有 break ,比對成功後不會自動向下執行其他case,而是跳出整個 switch , 但是可以使用 fallthrough 強制執行後面的case代碼。
integer := 6
switch integer {
case 4:
fmt.Println("The integer was <= 4")
fallthrough
case 5:
fmt.Println("The integer was <= 5")
fallthrough
case 6:
fmt.Println("The integer was <= 6")
fallthrough
case 7:
fmt.Println("The integer was <= 7")
fallthrough
case 8:
fmt.Println("The integer was <= 8")
fallthrough
default:
fmt.Println("default case")
}
上面的程式将輸出
The integer was <= 6
The integer was <= 7
The integer was <= 8
default case
此書的說法和例子都沒有錯, 但不夠直白, 象我這樣看書不認真的人, 就錯過了重點.
寫得比較淺顯直白的, 是《go 學習筆記》p26:
如需要繼續下一分支,可使用 fallthrough,但不再判斷條件。
x := 10
switch x {
case 10:
println("a")
fallthrough
case 0:
println("b")
}
輸出:
a
b
runoob.com裡的教程, 是寫得最清楚明白的:
使用 fallthrough 會強制執行後面的 case 語句,fallthrough 不會判斷下一條 case 的表達式結果是否為 true。
package main
import "fmt"
func main() {
switch {
case false:
fmt.Println("1、case 條件語句為 false")
fallthrough
case true:
fmt.Println("2、case 條件語句為 true")
fallthrough
case false:
fmt.Println("3、case 條件語句為 false")
fallthrough
case true:
fmt.Println("4、case 條件語句為 true")
case false:
fmt.Println("5、case 條件語句為 false")
fallthrough
default:
fmt.Println("6、預設 case")
}
}
以上代碼執行結果為:
2、case 條件語句為 true
3、case 條件語句為 false
4、case 條件語句為 true
從以上代碼輸出的結果可以看出:switch 從第一個判斷表達式為 true 的 case 開始執行,如果 case 帶有 fallthrough,程式會繼續執行下一條 case,且它不會去判斷下一個 case 的表達式是否為 true。
讓我慶幸的是, fallthrough很不常用, 是以我範了這麼低級的了解錯誤, 這麼多年也沒有"翻車".