Golang Switch/Case 关键字
最后修改于 2025 年 5 月 7 日
本教程将讲解如何在 Go 中使用 switch 和 case 关键字。我们将通过 switch/case 语句的实际示例来介绍条件逻辑基础。
switch/case 结构根据表达式的值提供多路分支。它使用 switch 来定义控制流,使用 case 来指定条件。在许多情况下,它比多个 if-else 语句更清晰。
在 Go 中,switch 和 case 支持多种形式:表达式 switch、类型 switch 和用于特殊控制流的 fallthrough。它们共同构成了一个用于决策的通用工具。
基本 switch/case 语句
最简单的形式使用 switch 来评估一个表达式,并使用 case 来匹配特定值。本示例演示了使用数字进行基本 switch/case 用法。
package main
import "fmt"
func main() {
num := 3
switch num {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
default:
fmt.Println("Unknown number")
}
}
switch 评估 num,每个 case 检查是否匹配。如果没有任何 case 匹配,则运行 default case。在 Go 中,case 子句会自动中断,无需显式 break 语句。
带表达式的 Switch/case
Go 允许在 case 子句中使用表达式,从而实现复杂的条件。本示例展示了如何在 switch/case 中使用比较。
package main
import "fmt"
func main() {
score := 85
switch {
case score >= 90:
fmt.Println("Grade: A")
case score >= 80:
fmt.Println("Grade: B")
case score >= 70:
fmt.Println("Grade: C")
case score >= 60:
fmt.Println("Grade: D")
default:
fmt.Println("Grade: F")
}
}
在 switch 后面不带表达式时,case 子句的作用类似于 if-else 链。每个 case 都评估一个条件,并执行第一个为真的 case。这种方法提高了可读性。
带多个值的 Switch/case
单个 case 可以测试多个以逗号分隔的值。本示例使用 switch/case 检查元音字母。
package main
import "fmt"
func main() {
char := 'e'
switch char {
case 'a', 'e', 'i', 'o', 'u':
fmt.Printf("%c is a vowel\n", char)
case 'y':
fmt.Printf("%c is sometimes a vowel\n", char)
default:
fmt.Printf("%c is a consonant\n", char)
}
}
带有多个值的 case 可以匹配任何列出的元音字母。这使得代码简洁明了。此处的 switch 与 rune(字符)一起使用。
Switch/case 中的 Fallthrough
Go 的 fallthrough 关键字用于 case 内部,将控制转移到下一个 case。本示例演示了其行为。
package main
import "fmt"
func main() {
num := 2
switch num {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
fallthrough
case 3:
fmt.Println("Three")
case 4:
fmt.Println("Four")
default:
fmt.Println("Unknown")
}
}
当 num 为 2 时,case 打印 "Two" 并使用 fallthrough 来执行下一个 case,打印 "Three"。与许多语言不同,Go 需要显式的 fallthrough 才能继续到下一个 case。
带 case 的类型 switch
Go 的类型 switch 使用 switch 和 case 来检查接口变量的类型。本示例识别不同的类型。
package main
import "fmt"
func checkType(x interface{}) {
switch x.(type) {
case int:
fmt.Println("Integer")
case float64:
fmt.Println("Float64")
case string:
fmt.Println("String")
case bool:
fmt.Println("Boolean")
default:
fmt.Println("Unknown type")
}
}
func main() {
checkType(42)
checkType(3.14)
checkType("hello")
checkType(true)
}
switch x.(type) 语法与 case 子句配对以匹配特定类型。这对于 Go 中的动态类型处理非常有用。
带初始化的 Switch/case
switch 语句可以包含一个初始化子句,而 case 子句定义条件。本示例演示了此功能。
package main
import (
"fmt"
"time"
)
func main() {
switch hour := time.Now().Hour(); {
case hour < 12:
fmt.Println("Good morning!")
case hour < 17:
fmt.Println("Good afternoon!")
default:
fmt.Println("Good evening!")
}
}
switch 初始化了作用域限定在代码块中的 hour 变量,每个 case 都评估一个条件。这使得相关逻辑保持紧凑。
实际示例:命令处理器
本示例使用 switch 和 case 来构建一个命令处理器,展示其在实际应用中的用法。
package main
import (
"fmt"
"strings"
)
func processCommand(cmd string) {
switch strings.ToLower(cmd) {
case "start":
fmt.Println("Starting system...")
case "stop":
fmt.Println("Stopping system...")
case "status":
fmt.Println("System is running")
case "help", "?":
fmt.Println("Available commands: start, stop, status, help")
default:
fmt.Println("Unknown command")
}
}
func main() {
processCommand("start")
processCommand("HELP")
processCommand("invalid")
}
switch 处理命令,每个 case 处理一个特定的命令。case 中的多个值(例如 "help", "?")映射到同一操作。default case 处理无效输入。
来源
本教程涵盖了 Go 中的 switch 和 case 关键字,并演示了它们在各种条件逻辑场景中的用法。