Golang中switch的用法小结

通常语法结构:

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default://可以没有
        ...
}

注:

  • 可以在一个 case 中包含多个表达式,每个表达式用逗号分隔

    switch letter {
        case "a", "e", "i", "o", "u": //multiple expressions in case
            fmt.Println("vowel")
        default:
            fmt.Println("not a vowel")
        }
    

没有表达式的 switch

switch 中的表达式是可选的,可以省略。如果省略表达式,则相当于 switch true,这种情况下会将每一个 case 的表达式的求值结果与 true 做比较,如果相等,则执行相应的代码。

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 后面没有表达式因此被认为是 switch true 并对每一个 case 表达式的求值结果与 true 做比较。case num >= 51 && num <= 100:的求值结果为 true,因此程序输出:num is greater than 51 and less than 100。这种类型的 switch 语句可以替代多重 if else 子句。

参考

posted @ 2020-11-11 13:24  TR_Goldfish  阅读(207)  评论(0编辑  收藏  举报