golang的switch語句使用fallthrough

很多的教程在說明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很不常用, 所以我範了這麼低級的理解錯誤, 這麼多年也沒有"翻車".

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章