switch 语句中的每一个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止。
Go中 switch 语句case匹配项后面不需要加 break。默认 case 最后自带 break ,匹配成功后不会执行其他 case,如果需要执行后面的 case,可以用 fallthrough 。
golang中的switch语句能干嘛?
1、用作等值判断
switch var1 {
case val1:
...
case val2:
...
default:
...
}
2、用作多重if判断
switch 中的表达式可以省略。如果省略,则相当于 switch true,此时会将每个 case 表达式的求值结果与 true 比较,如果为真,则执行对应代码。
switch { //相当于switch true
case 逻辑判断表达式1:
...
case 逻辑判断表达式2:
...
default:
...
}
举例:
func main() {
grade := "C"
marks := 80
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50,60,70 : grade = "C"
default: grade = "D"
}
switch {
case grade == "A" :
fmt.Printf("优秀!\n" )
case grade == "B", grade == "C" :
fmt.Printf("良好\n" )
default:
fmt.Printf("差\n" )
}
fmt.Printf("你的等级是 %s\n", grade )
}
3、用于 type-switch 判断 interface 变量中存储的变量类型
Type Switch 是 Go 语言中一种特殊的 switch 语句,它判断某个接口变量的类型而不是具体的值,然后根据类型再做处理。在 Type Switch 语句的 case 子句中不能用 fallthrough。
switch x.(type){
case type:
statement(s)
case type:
statement(s)
/* 可以定义任意个数的case */
default: /* 可选 */
statement(s)
}
举例:
func main() {
var x interface{}
switch i := x.(type) {
case nil:
fmt.Printf(" x 的类型 :%T",i)
case int:
fmt.Printf("x 是 int 型")
case bool, string:
fmt.Printf("x 是 bool 或 string 型" )
default:
fmt.Printf("未知型")
}
}
4、fallthrough
在switch语句中使用 fallthrough 会强制执行后面的 case 语句,即 fallthrough 不会判断下一个case 的结果是否为 true。
func main() {
x := 1
switch x {
case 0:
fmt.Println("1、case 条件语句为 0")
fallthrough
case 1:
fmt.Println("2、case 条件语句为 1")
fallthrough
case 2:
fmt.Println("3、case 条件语句为 2")
fallthrough
case 3:
fmt.Println("4、case 条件语句为 3")
default:
fmt.Println("默认 case")
}
}