Files
go-basics/stage02-control-flow/02-switch
2026-03-13 23:54:07 +08:00
..
2026-03-13 23:54:07 +08:00
2026-03-13 23:54:07 +08:00
2026-03-13 23:54:07 +08:00

02-switch - switch语句

知识点讲解

基本switch语法

switch value {
case value1:
    // 当value == value1时执行
case value2:
    // 当value == value2时执行
default:
    // 当value不等于任何case时执行
}

switch重要特性

  1. 自动break:Go的switch不需要显式break,执行完case后自动跳出
  2. fallthrough:使用fallthrough关键字继续执行下一个case
  3. 多值匹配:一个case可以匹配多个值
  4. 无表达式的switch:相当于if-else if-else的替代
  5. 类型switch:用于类型断言

多值匹配

switch day {
case "Monday", "Tuesday":
    fmt.Println("工作日")
}

fallthrough

switch num {
case 1:
    fmt.Println("one")
    fallthrough  // 继续执行case 2
case 2:
    fmt.Println("two")
}

无表达式的switch

switch {
case score >= 90:
    fmt.Println("优秀")
case score >= 80:
    fmt.Println("良好")
}

类型switch

switch v := i.(type) {
case int:
    fmt.Println("整数")
case string:
    fmt.Println("字符串")
}

学习目标

完成本练习后,你将:

  • ✅ 掌握switch语句的基本用法
  • ✅ 理解多值匹配和fallthrough
  • ✅ 学会使用无表达式的switch
  • ✅ 了解类型switch的使用

练习说明

打开 main.go,根据注释提示填充代码,完成后运行 go test -v 验证答案。