Go语言中switch case无需break,自动匹配执行对应分支,支持带值和无表达式(布尔条件)两种形式,比C/Java更安全灵活。

在Go语言中,switch case 是一种常用的流程控制结构,用于根据变量或表达式的值执行不同的代码分支。与C、Java等语言相比,Go的 switch 更加灵活和安全,不需要手动写 break 来防止“穿透”,默认就只执行匹配的分支。
Go 中 switch 的基本形式如下:
switch 表达式 {
case 值1:
// 执行语句
case 值2, 值3: // 可以匹配多个值
// 执行语句
default:
// 默认情况
}
例如:
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
// 输出:Wednesday
Go 支持不带表达式的 switch,此时 case 后应为布尔表达式。这种写法类似于 if-else 链,但更清晰。
立即学习“go语言免费学习笔记(深入)”;
age := 25
switch {
case age < 18:
fmt.Println("未成年")
case age >= 18 && age < 60:
fmt.Println("成年人")
default:
fmt.Println("老年人")
}
// 输出:成年人
一个 case 可以匹配多个值,用逗号分隔。如果想手动“穿透”到下一个 case,使用 fallthrough 关键字。
ch := 'a'
switch ch {
case 'a', 'A':
fmt.Println("Letter A")
fallthrough
case 'b', 'B':
fmt.Println("Letter B")
default:
fmt.Println("Other")
}
// 输出:
// Letter A
// Letter B
注意:fallthrough 不判断下一个 case 条件是否成立,直接执行其语句块。
switch 还可用于判断接口值的具体类型,这在处理 interface{} 类型时非常有用。
var x interface{} = "hello"
switch v := x.(type) {
case string:
fmt.Printf("字符串: %s\n", v)
case int:
fmt.Printf("整数: %d\n", v)
case nil:
fmt.Println("nil值")
default:
fmt.Printf("未知类型: %T\n", v)
}
// 输出:字符串: hello
其中 v := x.(type) 是类型断言的特殊用法,只能在 switch 中使用。
基本上就这些。Go 的 switch 设计简洁,避免了传统语言中常见的错误,同时提供了足够的灵活性应对各种场景。以上就是switch case流程控制在Golang中如何实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号