Go switch

Go 的 switch 语句可以从多个条件中执行一个语句。它类似于 if-else-if 链语句。

语法:

switch  var1 {  
case val1:  
.....  
case val2  
.....  
default:  
.....  
}  

在Go语言中,switch语句更加灵活。在上述语法中,var1是一个可以是任何类型的变量,而val1val2等是var1可能的取值。

switch语句中,一个case语句可以测试多个值,这些值以逗号分隔。

例如:case val1, val2, val3:

如果匹配到任何一个case,就会执行相应的case语句。在Go语言的switch语句中,默认情况下不会出现自动的case穿透,因为break关键字是隐式的。

要在Go语言的switch语句中实现穿透,可以在分支的末尾使用关键字"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 故障示例

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

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想