Golang switch 语句

简介

switch 语句提供了一种简洁的方式来执行多路分支选择

基本使用

  1. 基本语法如下:
switch expression {
case value1:
    // 当 expression 的值等于 value1 时执行
case value2:
    // 当 expression 的值等于 value2 
  1. switch 的每个分支自动提供了隐式的 break,意味着只有第一个匹配的 case 会被执行。不需要显式地在每个 case 后面加 break

  2. 如果你想要一个 case 执行后继续检查下一个 case,可以使用 fallthrough 语句:

switch x {
case 1:
    fmt.Println("x is 1")
    fallthrough
case 2:
    fmt.Println("x is 2")
    fallthrough
case 3:
    fmt.Println("x is 3")
default:
    fmt.Println("x is not 1, 2, or 3")
}

在上面的代码中,如果 x 是 1,它会打印出 “x is 1” 和 “x is 2”,因为 fallthrough 语句导致程序继续执行下一个 case

  1. switch 也支持不带表达式的用法,其中每个 case 可以包含一个条件表达式:
y := 20

switch {
case y > 10:
    fmt.Println("y is greater than 10")
case y == 10:
    fmt.Println("y is exactly 10")
default:
    fmt.Println("y is less than 10")
}

在这种情况下,switch 语句类似于一系列的 if-else 语句,但其语法更加清晰

  1. switch 也可以包含初始化语句,类似于 if 语句:
switch z := computeValue(); {
case z > 10:
    fmt.Println("z is greater than 10")
case z == 10:
    fmt.Println("z is exactly 10")
default:
    fmt.Println("z is less than 10")
}

常见用法

  • 类型判断: switch 可以用来进行类型判断,在这种情况下,它会匹配一个接口变量的动态类型
var i interface{} = /* 一个值 */

switch t := i.(type) {
case string:
    fmt.Println("i is a string:", t)
case int:
    fmt.Println("i is an int:", t)
default:
    fmt.Printf("Unknown type %T\n", t)
}

在这个例子中,i.(type) 用来发现接口变量 i 的动态类型
注意:i.(type) 用于 switch 语句中进行类型断言的类型判断。它只能在 switch 的类型判断分支中使用,不可以单独使用在其他地方

  • 多值匹配: 你可以在一个 case 语句中测试多个值。这可以简化代码,避免编写多个具有相同结果的 case 语句
switch x {
case 1, 2, 3:
    fmt.Println("x is 1, 2 or 3")
default:
    fmt.Println("x is not 1, 2, or 3")
}
  • 条件组合: case 语句中可以包含多个条件,这些条件可以是逻辑表达式
switch {
case x > 0 && x < 10:
    fmt.Println("x is between 1 and 9")
case x == 10 || x == 20:
    fmt.Println("x is either 10 or 20")
}
  • 无条件的 switch: 无条件的 switch 相当于一个更优雅的 if-else 链
switch {
case score >= 90:
    fmt.Println("Grade: A")
case score >= 80:
    fmt.Println("Grade: B")
case score >= 70:
    fmt.Println("Grade: C")
default:
    fmt.Println("Grade: F")
}
  • 退出循环: 在循环内部,switch 可以与 break 语句一起使用来退出循环
for {
    switch {
    case someCondition():
        fmt.Println("Condition met")
        break // 默认只会跳出 switch
    default:
        fmt.Println("Default case")
    }
    break // 退出 for 循环
}

请注意,在这种情况下,break 语句只会退出 switch,而不是循环。要退出循环,需要在外部再次使用 break 语句

  • 跳过当前迭代: 在循环中使用 switch,可以配合 continue 语句来跳过当前迭代
for x := 0; x < 5; x++ {
    switch {
    case x%2 == 0:
        // 跳过偶数
        continue
    }
    fmt.Println("Odd:", x)
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值