switch语句中的表达式是可选的,可以省略。如果表达式被省略,则认为switch
为true
,并对每个case
表达式求值,为真则执行相应的代码块。
package main
import (
"fmt"
)
func main() {
num := 75
switch { // expression is omitted
case num >= 0 && num <= 50:
fmt.Println("num is greater than 0 and less than 50")
case num >= 51 && num <= 100:
fmt.Println("num is greater than 51 and less than 100")
case num >= 101:
fmt.Println("num is greater than 100")
}
}
在上面的程序中,switch中不存在表达式,因此它被认为是true
,并对每种case
求值。case num >= 51 && num <= 100:
为真,程序输出num is greater than 51 and less than 100
。
这种类型的switch
可以作为多个if else
子句的替代。