go语言 – 没有表达式的switch

switch语句中的表达式是可选的,可以省略。如果表达式被省略,则认为switchtrue,并对每个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子句的替代。



浙ICP备17015664号-1 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载