zoukankan      html  css  js  c++  java
  • 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出会被执行。

  • 相关阅读:
    正则表达式
    内涵函数二
    内置函数
    生成器的推导式 表达式
    函数的闭包 迭代器的使用
    函数的动态参数,命名空间
    函数
    文件的操作
    set 集合 拷贝的操作
    u-boot简介
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/6484956.html
Copyright © 2011-2022 走看看