Go语言switch语句

Go语言switch语句教程

Go 语言switch 语句 后面不需要再加 break 语句,case 语句最后自带 break 语句。 如果我们执行完匹配的 case 后,还需要继续执行后面的 case,可以使用 fallthrough 。

Go语言的 switch 语句支持多个 case 连写的形式,即如果多个 case 执行相同的情况,则可以使用逗号分隔,写在一行。

Go语言switch语句简写

语法

switch var1 { case val1, val2: ... case val3, val4: ... default: ... }

说明

如果 var1 满足条件 val1 或者条件 val2,都执行同样的代码,那么我们就可以将 val1 和 val2 写在同一行,使用 , 分割。

如果 var1 满足条件 val3 或者条件 val4,都执行同样的代码,那么我们就可以将 val3 和 val4 写在同一行,使用 , 分割,都不满足,就执行 default 语句。

案例

使用switch语句,fallthrough执行多个case

使用 switch 语句,fallthrough 执行多个 case

package main import "fmt" func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用switch语句,fallthrough执行多个case var b = false switch b { case true: fmt.Println("Case 1 true") fallthrough case false: fmt.Println("Case 2 false") fallthrough case true: fmt.Println("Case 3 true") fallthrough case false: fmt.Println("Case 4 false") fallthrough default: fmt.Println("default") } }

程序运行后,控制台输出如下:

33_golang switch.png

我们定义了一个 bool 变量 b,接着我们使用 switch 语句判断 b,同时,我们在每一个 case 的最后都加了一个 fallthrough。

因为 case 2 是匹配的,所以输出了 case 2 的代码,虽然 case 3 是不匹配的,但因为我们使用了 fallthrough 强制执行后面的代码,所以 case 3,case 4 和 default 的代码块都被执行了。

使用switch语句,case连写

使用 switch 语句,case 连写

package main import "fmt" func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用switch语句,case连写 score := 70 switch score { case 90, 85: fmt.Println("excellent") case 80, 70: fmt.Println("Good") case 60: fmt.Println("Pass") default: fmt.Println("Strive") } }

程序运行后,控制台输出如下:

34_golang switch.png

我们定义了一个 整数 变量 score,接着我们使用 switch 语句判断 score,如果是 90 或者 85,则输出 excellent,如果是 80 或者 70,则输出 Good,如果是 60,则输出 Pass,其他情况,输出 Strive。

因为,我们的值为 70,因此输出了 Good。

Go语言switch语句总结

在 Go 语言中,如果我们执行完匹配的 case 后,还需要继续执行后面的 case,可以使用 fallthrough 。

Go 语言的 switch 语句支持多个 case 连写的形式,即如果多个 case 执行相同的情况,则可以使用逗号分隔,写在一行。