Go的switch语句默认自动跳出,避免fallthrough陷阱,支持表达式和类型判断,使多分支逻辑更清晰安全。

Golang的
switch
if-else if
case
switch
fallthrough
在Golang中,
switch
if-else if
最基础的用法,你可以在
switch
case
package main
import "fmt"
func main() {
score := 85
switch score / 10 { // 这里对score进行整数除法,得到一个范围
case 10, 9: // 可以匹配多个值
fmt.Println("优秀")
case 8:
fmt.Println("良好")
case 7:
fmt.Println("中等")
case 6:
fmt.Println("及格")
default: // 所有case都不匹配时执行
fmt.Println("不及格")
}
// switch语句也可以没有表达式,此时case后面直接跟布尔表达式
age := 25
switch { // 没有表达式
case age < 18:
fmt.Println("未成年")
case age >= 18 && age < 60:
fmt.Println("成年人")
default:
fmt.Println("老年人")
}
// fallthrough关键字:明确要求执行下一个case
// 这是一个需要谨慎使用的特性,因为它打破了Go switch的默认行为
// 多数情况下,我们希望避免它,因为它可能导致逻辑混乱
num := 2
switch num {
case 1:
fmt.Println("Case 1")
fallthrough // 会执行下一个case
case 2:
fmt.Println("Case 2")
// 如果这里没有fallthrough,则不会执行Case 3
case 3:
fmt.Println("Case 3")
default:
fmt.Println("Default case")
}
// 上面的输出会是 "Case 2" 和 "Case 3"
}值得一提的是,Go的
switch
case
case
switch
break
fallthrough
立即学习“go语言免费学习笔记(深入)”;
switch
if-else if
这是一个老生常谈的问题,但对于Go语言来说,答案并非一概而论,它更多地取决于你的具体场景和代码的意图。我个人认为,当你的条件判断是基于同一个变量或表达式的不同值时,
switch
switch
然而,如果你的条件是多个不相关的布尔表达式,或者每个条件都非常复杂,
if-else if
switch
switch {}case
if-else if
if-else if
我的经验是,不要为了用
switch
if
if
switch
if-else if
switch
break
Golang
switch
break
case
break
case
break
我记得刚开始写Go的时候,总会下意识地敲
break
case
当然,如果你确实需要那种“穿透”行为,
fallthrough
fallthrough
switch
fallthrough
break
switch
type switch
type switch
它的语法有些特殊,通常是
switch v := i.(type)
i
case
v
case
package main
import "fmt"
// 定义一个接口
type Shape interface {
Area() float64
}
// 定义几个实现Shape接口的结构体
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14159 * c.Radius * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func DescribeShape(s Shape) {
switch v := s.(type) { // 这里的v在每个case中会是不同的具体类型
case Circle:
fmt.Printf("这是一个圆形,半径 %.2f,面积 %.2f\n", v.Radius, v.Area())
// 在这里,v已经是Circle类型,可以直接访问其字段Radius
case Rectangle:
fmt.Printf("这是一个矩形,宽 %.2f,高 %.2f,面积 %.2f\n", v.Width, v.Height, v.Area())
// 在这里,v已经是Rectangle类型,可以直接访问其字段Width和Height
case nil: // 处理nil接口的情况
fmt.Println("这是一个空形状 (nil)")
default: // 处理其他未知类型
fmt.Printf("这是一个未知形状,类型是 %T\n", v)
}
}
func main() {
c := Circle{Radius: 5}
r := Rectangle{Width: 4, Height: 6}
var sNil Shape // 一个nil接口
DescribeShape(c)
DescribeShape(r)
DescribeShape(sNil)
DescribeShape("我不是一个形状") // 传递一个非Shape类型的值(虽然这在编译时会报错,这里仅为演示default case)
}(注:
DescribeShape("我不是一个形状")Shape
Area()
default
default
我发现
type switch
interface{}if v, ok := i.(TypeX); ok {}以上就是Golangswitch语句使用及分支条件解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号