go語言fallthrough的用法心得

fallthrough:Go裏面switch默認至關於每一個case最後帶有break,匹配成功後不會自動向下執行其餘case,而是跳出整個switch, 可是能夠使用fallthrough強制執行後面的case代碼。spa

示例程序1:code

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")
    }

輸出結果:blog

The integer was <= 5
The integer was <= 6
The integer was <= 7
The integer was <= 8get

問題:是否在switch最後一個分支使用fallthrough???it

image

有錯誤提示,顯示:cannot fallthrough final case in switchclass

fallthrough不能用在switch的最後一個分支。變量

示例程序2:程序

上述示例是true、false常量進行分支判斷,看以下變量示例。im

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")
    }

輸出結果以下:d3

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分支中使用變量進行判斷的時,fallthrough正確的分支開始其做用。

相關文章
相關標籤/搜索