← for 循环 | defer 延迟 →

switch 分支 - Go 流程控制

switch 语句是多分支选择结构,Go 的 switch 灵活强大,支持类型 switch、fallthrough 等特性,是处理多条件分支的利器。

📌 核心概念

🔀

多分支

case 匹配

switch
📝

初始化语句

switch 前初始化

if x := f();

fallthrough

穿透执行

穿透 case
🔍

类型 switch

类型判断

type switch

基础用法

📝 switch 基本形式

package main

import (
    "fmt"
    "time"
)

func main() {
    // 基本 switch
    day := time.Now().Weekday()
    
    switch day {
    case time.Saturday, time.Sunday:
        fmt.Println("Weekend!")
    default:
        fmt.Println("Workday")
    }
    
    // switch 返回布尔值
    num := 5
    switch {
    case num < 5:
        fmt.Println("less than 5")
    case num == 5:
        fmt.Println("equals 5")
    case num > 5:
        fmt.Println("greater than 5")
    }
}

💡 switch 要点

  • 自动 break: Go 的 case 自动 break,不需要显式写
  • 括号可选: 条件不需要括号
  • 多条件: 一个 case 可以有多个值
  • 无条件 switch: switch {} 类似 if-else 链

初始化语句

📝 switch 前初始化

package main

import "fmt"

func main() {
    // 带初始化语句的 switch
    switch x := getValue(); x {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    default:
        fmt.Println("other")
    }
    // x 在这里不可用
}

func getValue() int {
    return 1
}

fallthrough 穿透

📝 fallthrough 用法

package main

import "fmt"

func main() {
    // fallthrough: 执行下一个 case
    for i := 0; i < 3; i++ {
        switch i {
        case 0:
            fmt.Println("zero")
            fallthrough // 继续执行下一个 case
        case 1:
            fmt.Println("one")
            fallthrough
        case 2:
            fmt.Println("two")
        }
        fmt.Println("---")
    }
    // 输出:
    // i=0: zero → one → two
    // i=1: one → two
    // i=2: two
    
    // ⚠️ fallthrough 必须是 case 的最后一个语句
}

类型 switch

📝 类型判断

package main

import "fmt"

func main() {
    var values = []interface{}{42, "hello", 3.14, true}
    
    for _, v := range values {
        switch x := v.(type) {
        case int:
            fmt.Printf("Integer: %d\n", x)
        case string:
            fmt.Printf("String: %s\n", x)
        case float64:
            fmt.Printf("Float: %f\n", x)
        case bool:
            fmt.Printf("Boolean: %v\n", x)
        default:
            fmt.Printf("Unknown type: %T\n", x)
        }
    }
}

// 类型 switch 要点:
// 1. 使用 .(type) 语法
// 2. case 后面是类型而不是值
// 3. 变量 x 在每个 case 中有对应类型

实用模式

1. 状态机

📝 状态处理

type State int

const (
    StateIdle State = iota
    StateRunning
    StatePaused
    StateStopped
)

func handleState(state State) {
    switch state {
    case StateIdle:
        fmt.Println("Starting...")
    case StateRunning:
        fmt.Println("Processing...")
    case StatePaused:
        fmt.Println("Paused")
    case StateStopped:
        fmt.Println("Stopped")
    default:
        fmt.Println("Unknown state")
    }
}

2. 命令分发

📝 命令处理

func handleCommand(cmd string, args []string) {
    switch cmd {
    case "start", "run":
        startService(args)
    case "stop", "exit":
        stopService()
    case "restart":
        restartService()
    case "status":
        showStatus()
    default:
        fmt.Printf("Unknown command: %s\n", cmd)
    }
}

最佳实践

✅ switch 使用建议

  • 多分支优先: 3 个以上分支用 switch
  • 默认 case: 始终包含 default 处理未知情况
  • 慎用 fallthrough: 除非确实需要穿透
  • 类型 switch: 处理 interface{} 的好工具

📖 延伸阅读