package main
import "fmt"
func main() {
var num1 int = 100
switch num1 {
case 98, 99:
fmt.Println("It's equal to 98")
case 100:
fmt.Println("It's equal to 100")
default:
fmt.Println("It's not equal to 98 or 100")
}
}
输出:
It's equal to 100
switch {
case condition1:
...
case condition2:
...
default:
...
}
例如:
switch {
case i < 0:
f1()
case i == 0:
f2()
case i > 0:
f3()
}
任何支持进行相等判断的类型都可以作为测试表达式的条件,包括 int、string、指针等。
package main
import "fmt"
func main() {
var num1 int = 7
switch {
case num1 < 0:
fmt.Println("Number is negative")
case num1 > 0 && num1 < 10:
fmt.Println("Number is between 0 and 10")
default:
fmt.Println("Number is 10 or greater")
}
}
输出:
Number is between 0 and 10
switch 语句的第三种形式是包含一个初始化语句:
switch initialization {
case val1:
...
case val2:
...
default:
...
}
这种形式可以非常优雅地进行条件判断:
switch result := calculate(); {
case result < 0:
...
case result > 0:
...
default:
// 0
}
在下面这个代码片段中,变量 a 和 b 被平行初始化,然后作为判断条件:
switch a, b := x[i], y[j]; {
case a < b: t = -1
case a == b: t = 0
case a > b: t = 1
}
问题 5.1:
请说出下面代码片段输出的结果:
k := 6
switch k {
case 4:
fmt.Println("was <= 4")
fallthrough
case 5:
fmt.Println("was <= 5")
fallthrough
case 6:
fmt.Println("was <= 6")
fallthrough
case 7:
fmt.Println("was <= 7")
fallthrough
case 8:
fmt.Println("was <= 8")
fallthrough
default:
fmt.Println("default case")
}