借助fallthrough
语句,即使表达式不匹配,我们也可以在switch case语句执行后立即转移程序控制权。通常,控制会在匹配后第一行执行后立即从 switch 语句中出来。不要把下通的开关情况下的最后一条语句。
示例 1:在此示例中,我们可以看到通过使用带有fallthrough 的switch case 并假设变量为字符串类型,我们可以使用 switch case。
// Golang program to show the
// uses of fallthrough keyword
package main
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
// Main function
func main() {
day := "Tue"
// Use switch on the day variable.
switch {
case day == "Mon":
fmt.Println("Monday")
fallthrough
case day == "Tue":
fmt.Println("Tuesday")
fallthrough
case day == "Wed":
fmt.Println("Wednesday")
}
}
输出 :
Tuesday
Wednesday
示例 2:
// Golang program to show the
// uses of fallthrough keyword
package main
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
// Main function
func main() {
gfg := "Geek"
// Use switch on the day variable.
switch {
case gfg == "Geek":
fmt.Println("Geek")
fallthrough
case gfg == "For":
fmt.Println("For")
fallthrough
case gfg == "Geeks":
fmt.Println("Geeks")
}
}
输出 :
Geek
For
Geeks