go語言fallthrough的用法心得


fallthrough:Go里面switch默認相當於每個case最后帶有break,匹配成功后不會自動向下執行其他case,而是跳出整個switch, 但是可以使用fallthrough強制執行后面的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")
    }

輸出結果:

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

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

image

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

fallthrough不能用在switch的最后一個分支。

示例程序2:

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

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

輸出結果如下:

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正確的分支開始其作用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM