📅  最后修改于: 2021-01-02 09:06:26             🧑  作者: Mango
Go switch语句从多个条件中执行一个语句。它类似于if-else-if链语句。
句法:
switch var1 {
case val1:
.....
case val2
.....
default:
.....
}
Go中的switch语句更加灵活。在上面的语法中,var1是可以是任何类型的变量,并且val1,val2,…是var1的可能值。
在switch语句中,在一种情况下可以测试多个值,这些值以逗号分隔的列表形式显示
例如:情况val1,val2,val3:
如果匹配任何大小写,则执行相应的case语句。在这里,break关键字是隐式的。因此,自动掉线不是Go switch语句中的默认行为。
对于Go switch语句中的穿透,在分支的末尾使用关键字“ fallthrough”。
转到开关示例:
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
转到开关失败示例
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