Golang 使用fallthrough关键字
使用 fallthrough 语句,我们可以在 switch 语句中执行完一个 case 语句后,跳至下一个 case 语句。即使表达式不匹配,程序也能转移控制。通常情况下,在 switch 语句执行完一个匹配项的第一行后,程序将跳出语句。不要在 switch case 的最后一个语句使用 fallthrough。
示例 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