代码点读机 / Go / fallthrough

fallthrough Go · 关键字

switch 语句里的贯穿指令:显式告诉程序继续执行下一个 case 的代码。

怎么用

在 case 分支末尾写 fallthrough

小例子

package main
import "fmt"

func main() {
    n := 1
    switch n {
    case 1:
        fmt.Println("一")
        fallthrough
    case 2:
        fmt.Println("二")
    }
}

运行结果

输出
一
二

提醒:Go 的 case 默认自动 break,只有明确需要贯穿时才写 fallthrough

官方文档:https://go.dev/ref/spec#Switch_statements

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Go全部词条