golang switch_入门 1.8、Switch

Golang使用switch关键字来处理多分支判断,不过与其他语言有点不太一样,让我们来跟随示例学习Golang的switch吧

示例代码

package mainimport (  "fmt"  "time")func main(){  rank:=2;  fmt.Print("Rank is ")    //demo 1  switch rank{  case 1:    fmt.Println("the first");  case 2:    fmt.Println("the second");  case 3:    fmt.Println("the third");  }  //demo 2  switch time.Now().Hour(){  case 11,12,1:    fmt.Println("now is noon");  default:    fmt.Println("now is morning or afternoon");  }  //demo 3  switch{  case rank>1:    fmt.Println("Rank is not the first")  default:    fmt.Println("Rank is the first")  }  //demo 4  switch time.Now().Weekday(){  case time.Monday:    fmt.Println("through Monday")    fallthrough;  case time.Tuesday:    fmt.Println("through Tuesday")    fallthrough;  case time.Wednesday:    fmt.Println("through Wednesday")    fallthrough;  case time.Thursday:    fmt.Println("through Wednesday")    fallthrough;  case time.Friday:    fmt.Println("final Friday")  default:    fmt.Println("Weekend")  }}

Golang可使用 // 来做代码注释(注释的部分不会被编译或执行)

上面是完整的脚本代码,下面让我们跟着其中注释的demo位置来看switch的用法

常用用法
switch rank{  case 1:    fmt.Println("the first");  case 2:    fmt.Println("the second");  case 3:    fmt.Println("the third");  }

switch最简单常用的用法就是 对变量或值 直接switch,并使用case来对应不同的值处理不同的分支代码块(每个分支必须是不同的),执行代码结束后若没有特殊处理则会直接结束分支处理

若值没有case可匹配则处理default关键字处理的内容

这里大家要注意,Golang和其他语言的switch的区别,其他语言的switch正常没有处理break的话会继续顺序执行接下来的分支代码,但是Golang是直接跳出分支的,后面的demo会讲到如何利用fallthrough来让golang继续执行下面的分支

Case匹配多个值
switch time.Now().Hour(){  case 11,12,1:    fmt.Println("now is noon");  default:    fmt.Println("now is morning or afternoon");  }

case 中可指定多个不同的值来匹配处理相同的逻辑,上述代码即若当前时间的小时是11,12,1则都会处理第一条case的内容

Bool判断的case
switch{  case rank>1:    fmt.Println("Rank is not the first")  default:    fmt.Println("Rank is the first")  }

switch也可无需指定需要判断的变量或值,相当于使用true做分支判断,而case对应的则是判断条件(可以理解为case值为true/false),可方便的替代多层的 if/else 结构

fallthrough
switch time.Now().Weekday(){  case time.Monday:    fmt.Println("through Monday")    fallthrough;  case time.Tuesday:    fmt.Println("through Tuesday")    fallthrough;  case time.Wednesday:    fmt.Println("through Wednesday")    fallthrough;  case time.Thursday:    fmt.Println("through Wednesday")    fallthrough;  case time.Friday:    fmt.Println("final Friday")  default:    fmt.Println("Weekend")  }

这里主要用到 fallthrough 这个关键字,在demo 1中说到Golang的switch与其他语言的switch稍有所不同,是默认break的跳出分支,那 fallthrough 则是让开发者可以正常执行接下来的分支

switch在golang中特殊的处理方式是考虑到大部分开发过程中不太会出现需要继续执行下一条分支的情况,所以默认无需显式的break,但也提供fallthrough让开发者可以显示的继续执行


f41645795e1fbcabfe7282c4634a4774.png

“关注我,让迷惘的我找到你一起成长”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值