参考链接:https://studygolang.com/articles/13389

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代码。

 

测试用例:

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

  

 

相关文章:

  • 2021-06-07
  • 2021-10-04
  • 2019-02-28
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2021-12-26
猜你喜欢
  • 2021-12-25
  • 2022-12-23
  • 2021-06-20
  • 2021-08-29
  • 2021-09-02
  • 2022-01-20
相关资源
相似解决方案