简介
switch 语句提供了一种简洁的方式来执行多路分支选择
基本使用
- 基本语法如下:
switch expression {
case value1:
// 当 expression 的值等于 value1 时执行
case value2:
// 当 expression 的值等于 value2
switch 的每个分支自动提供了隐式的
break,意味着只有第一个匹配的case会被执行。不需要显式地在每个case后面加break如果你想要一个
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
- 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 语句,但其语法更加清晰
- 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)
}到此这篇关于golang switch语句的具体使用的文章就介绍到这了,更多相关golang switch语句内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论