Go的switch

go的switch

switch 是一个条件语句,用于多条件匹配,可以替换多个if else。

一、语法

var 变量

switch 变量 {
    case 值1:
    操作1

    case 值2:
    操作2
}

二、默认情况

所有条件都不符合,执行default情况

var a=8

switch a {
    case 8:
    fmt.Println("8")
    case 9:
    fmt.Println("9")
    case 10:
    fmt.Println("10")
    default: //上面所有条件都不符合,执行我
    fmt.Println("我不知道")
}

三、多表达式判断

case后可接多个条件。

var a=13

switch a {
    case 7,8,9:
    fmt.Println("7,8,9")
    case 10,11,12:
    fmt.Println("10,11,12")
    case 13,14,15,16,17:
    fmt.Println("13,14,15,16,17")
    default: //上面所有条件都不符合,执行我
    fmt.Println("我不知道")
}

四、无表达式

switch后不接变量。

// and 和 or    ----》 &&   ||
var a = 10
switch {
    case a == 8:
    fmt.Println("8")
    case a == 9:
    fmt.Println("9")
    case a == 10 || a==11:
    fmt.Println("10或11")
    default: 
    fmt.Println("我不知道")
}

五、Fallthrough

无条件执行下一个case中的代码。

var a = 8

switch {
    case a == 8:
    fmt.Println("8")
    fallthrough //无条件执行下一个case中的代码
    case a == 9:
    fmt.Println("9")
    fallthrough
    case a == 10:
    fmt.Println("10")
    default: //上面所有条件都不符合,执行我
    fmt.Println("我不知道")
}
posted @ 2020-03-29 21:43  Donner  阅读(205)  评论(0编辑  收藏  举报