全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-14 6 分钟 ✍️ juanwangdev

Go条件分支语句switch-case

Go switch语句简洁,每个case自动break,无需显式声明。

switch基本语法

基本结构

Go
switch 表达式 {
case 值1:
    // 处理
case 值2:
    // 处理
default:
    // 默认处理
}

// 示例
day := 3
switch day {
case 1:
    fmt.Println("周一")
case 2:
    fmt.Println("周二")
case 3:
    fmt.Println("周三")
default:
    fmt.Println("其他")
}

Go switch每个case自动break,无需显式写。

多值匹配

Go
day := 6
switch day {
case 1, 2, 3, 4, 5:
    fmt.Println("工作日")
case 6, 7:
    fmt.Println("周末")
default:
    fmt.Println("无效")
}

无表达式switch

类似if-else链

Go
score := 85
switch {  // 无表达式
case score >= 90:
    fmt.Println("优秀")
case score >= 80:
    fmt.Println("良好")
case score >= 60:
    fmt.Println("及格")
default:
    fmt.Println("不及格")
}

无表达式switch,case写条件表达式。

switch初始化语句

条件内声明

Go
switch n := len(s); n {
case 0:
    fmt.Println("空字符串")
case 1:
    fmt.Println("单字符")
default:
    fmt.Println("长度:", n)
}

// n仅在switch块内可见

结合函数

Go
switch err := doSomething(); {
case err == nil:
    fmt.Println("成功")
case err != nil:
    fmt.Println("失败:", err)
}

fallthrough穿透

继续执行下一个case

Go
n := 2
switch n {
case 1:
    fmt.Println("1")
    fallthrough
case 2:
    fmt.Println("2")
    fallthrough
case 3:
    fmt.Println("3")
default:
    fmt.Println("default")
}
// 输出:2, 3(穿透到下一个case)

fallthrough强制执行下一个case,不判断条件。

注意事项

Go
// fallthrough不判断条件,直接执行
// 只穿透到下一个case,不会穿透多个

n := 1
switch n {
case 1:
    fmt.Println("1")
    fallthrough  // 执行case 2(不管n是否等于2)
case 2:
    fmt.Println("2")
}

type switch类型选择

判断接口类型

Go
var i interface{} = 42

switch v := i.(type) {
case int:
    fmt.Println("int:", v)
case string:
    fmt.Println("string:", v)
default:
    fmt.Printf("其他类型: %T\n", v)
}

type switch用i.(type)语法,v在每个case中是具体类型。

switch特性对比

特性Go switch其他语言switch
默认break自动需显式写
多值匹配支持通常不支持
无表达式支持不支持
fallthrough需显式声明默认穿透
条件初始化支持不支持

switch使用示例

Go
func process(n int) {
    // 多值匹配
    switch n {
    case 0:
        fmt.Println("零")
    case 1, 2, 3:
        fmt.Println("小数")
    case 4, 5, 6, 7, 8, 9:
        fmt.Println("中数")
    default:
        fmt.Println("大数")
    }

    // 无表达式
    switch {
    case n < 0:
        fmt.Println("负数")
    case n == 0:
        fmt.Println("零")
    default:
        fmt.Println("正数")
    }
}

要点总结

  • switch每个case自动break,无需显式写
  • 多值匹配用逗号分隔:case 1, 2, 3
  • 无表达式switch用于条件判断,替代if-else链
  • 条件内声明变量:switch n := len(s); n
  • fallthrough穿透到下一个case(不判断条件)
  • type switch判断接口具体类型
  • default可选,处理未匹配情况
  • Go switch比其他语言更简洁安全

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go循环语句range
下一篇 → Go条件语句if-else
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库