Golang教程-Go switch

Go switch
Go 的 switch 语句可以从多个条件中执行一个语句。它类似于 if-else-if 链语句。
语法:
switch var1 {
case val1:
.....
case val2
.....
default:
.....
}
在Go语言中,switch
语句更加灵活。在上述语法中,var1
是一个可以是任何类型的变量,而val1
、val2
等是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