GO教程
GO控制语句
GO高级

Go switch

Go switch

Go switch 语句 从多个条件执行一个语句。类似于 if-else-if 链式语句。
语法:
switch  var1 {
case val1:
.....
case val2
.....
default:
.....
}
Go 中的 switch 语句更加灵活。在上面的语法中,var1 是一个可以是任何类型的变量,而 val1, val2, ... 是 var1 的可能值。
在 switch 语句中,一个以上的值可以被测试case,值显示在逗号分隔的列表中
like: case val1, val2, val3:
如果匹配任何 case,则对应的 case语句被执行。在这里,break 关键字是隐式的。所以自动失败不是 Go switch 语句中的默认行为。
对于 Go switch 语句中的 fall-through,在分支的末尾使用关键字"fallthrough"。
Go Switch 示例:
package main
import "fmt"
func main() {
   fmt.Print("Enter Number: ")
  var input int
  fmt.Scanln(&input)
   switch (input) {
  case 10:
      fmt.Print("the value is 10")
    case 20:
      fmt.Print("the value is 20")
    case 30:
      fmt.Print("the value is 30")
    case 40:
      fmt.Print("the value is 40")
    default:
      fmt.Print(" It is not 10,20,30,40 ")
   }
}
输出:
Enter Number: 20
the value is 20
输出:
Enter Number: 35
 It is not 10,20,30,40
Go switch fallthrough 示例
import "fmt"
func main() {
   k := 30
   switch k {
   case 10:
      fmt.Println("was <= 10"); fallthrough;
   case 20:
      fmt.Println("was <= 20"); fallthrough;
   case 30:
      fmt.Println("was <= 30"); fallthrough;
   case 40:
      fmt.Println("was <= 40"); fallthrough;
   case 50:
      fmt.Println("was <= 50"); fallthrough;
   case 60:
      fmt.Println("was <= 60"); fallthrough;
   default:
      fmt.Println("default case")
   }
}
输出:
was <= 30
was <= 40
was <= 50
was <= 60
default case

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4