golang的流程控制之switch

switch 语句中的每一个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止。

Go中 switch 语句case匹配项后面不需要加 break。默认 case 最后自带 break ,匹配成功后不会执行其他 case,如果需要执行后面的 case,可以用 fallthrough 。

golang中的switch语句能干嘛?

1、用作等值判断

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

 
2、用作多重if判断
switch 中的表达式可以省略。如果省略,则相当于 switch true,此时会将每个 case 表达式的求值结果与 true 比较,如果为真,则执行对应代码。

switch {        //相当于switch true
    case 逻辑判断表达式1:
        ...
    case 逻辑判断表达式2:
        ...
    default:
        ...
}

举例:

func main() {
    grade := "C"
    marks := 80
 
    switch marks {
    case 90: grade = "A"
    case 80: grade = "B"
    case 50,60,70 : grade = "C"
    default: grade = "D"
    }
 
    switch {
    case grade == "A" :
        fmt.Printf("优秀!\n" )
    case grade == "B", grade == "C" :
        fmt.Printf("良好\n" )
    default:
        fmt.Printf("差\n" )
    }
    fmt.Printf("你的等级是 %s\n", grade )
}

在这里插入图片描述
 
3、用于 type-switch 判断 interface 变量中存储的变量类型
Type Switch 是 Go 语言中一种特殊的 switch 语句,它判断某个接口变量的类型而不是具体的值,然后根据类型再做处理。在 Type Switch 语句的 case 子句中不能用 fallthrough。

switch x.(type){
    case type:
       statement(s)     
    case type:
       statement(s)
    /* 可以定义任意个数的case */
    default:       /* 可选 */
       statement(s)
}

举例:

func main() {
    var x interface{}
 
    switch i := x.(type) {
    case nil:
        fmt.Printf(" x 的类型 :%T",i)
    case int:
        fmt.Printf("x 是 int 型")
    case bool, string:
        fmt.Printf("x 是 bool 或 string 型" )
    default:
        fmt.Printf("未知型")
    }
}

在这里插入图片描述
 
4、fallthrough
在switch语句中使用 fallthrough 会强制执行后面的 case 语句,即 fallthrough 不会判断下一个case 的结果是否为 true。

func main() {
    x := 1
    switch x {
    case 0:
        fmt.Println("1、case 条件语句为 0")
        fallthrough
    case 1:
        fmt.Println("2、case 条件语句为 1")
        fallthrough
    case 2:
        fmt.Println("3、case 条件语句为 2")
        fallthrough
    case 3:
        fmt.Println("4、case 条件语句为 3")
    default:
        fmt.Println("默认 case")
    }
}

在这里插入图片描述

 
 
 
 

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值