Go中的switch fallthrough

 

 
switch sExpr {
case expr1:
    some instructions
case expr2: some other instructions case expr3: some other instructions default: other code } 

sExpr和expr1、expr2、expr3的类型必须一致。Go的switch非常灵活,表达式不必是常量或整数,执行的过程从上至下,直到找到匹配项;而如果switch没有表达式,它会匹配true。 Go里面switch默认相当于每个case最后带有break,匹配成功后不会自动向下执行其他case,而是跳出整个switch, 但是可以使用fallthrough强制执行后面的case代码。

http://play.golang.org/p/LySjbnt53q

package main

import "fmt"

func main() { switch { case false: fmt.Println("The integer was <= 4") fallthrough case true: fmt.Println("The integer was <= 5") fallthrough case false: fmt.Println("The integer was <= 6") fallthrough case true: fmt.Println("The integer was <= 7") case false: fmt.Println("The integer was <= 8") fallthrough default: fmt.Println("default case") } } 

运行结果:

The integer was <= 5

The integer was <= 6

The integer was <= 7

从本例可以看出:switch人第一个expr为true的case开始执行,如果case带有fallthrough,程序会继续执行下一条case,不会再判断下一条case的expr,如果之后的case都有fallthrough,default出会被执行。

转载于:https://www.cnblogs.com/lvdongjie/p/6484956.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言的switch case语法可以用于根据不同的条件执行不同的代码块。与其他语言相比,Go语言的switch case语法有以下几个特点: 1. 基本用法: ```go switch 变量 { case 值1: // 执行代码块1 case2: // 执行代码块2 default: // 执行默认代码块 } ``` 这是最基本的switch case语法,根据变量的值选择执行相应的代码块。 2. 一分支case多个并列值: ```go switch 变量 { case 值1, 值2, 值3: // 执行代码块 } ``` 可以在一个case语句指定多个并列的值,如果变量的值与任何一个值匹配,就会执行相应的代码块。 3. interface{}接口的类型判断: ```go switch 变量.(type) { case 类型1: // 执行代码块1 case 类型2: // 执行代码块2 default: // 执行默认代码块 } ``` 可以使用switch case语句对接口类型进行类型判断,根据不同的类型执行相应的代码块。 4. 跨越case的fallthrough: ```go switch 变量 { case 值1: // 执行代码块1 fallthrough case 值2: // 执行代码块2 } ``` 使用fallthrough关键字可以使程序执行完一个case后继续执行下一个case的代码块。 5. 分支表达式: ```go switch { case 表达式1: // 执行代码块1 case 表达式2: // 执行代码块2 default: // 执行默认代码块 } ``` 可以在switch语句省略变量,直接使用表达式进行判断。 这些是Go语言switch case语法的一些常见用法。根据不同的需求,可以灵活运用这些特性来编写逻辑清晰的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值