Golang初级系列教程-控制结构-switch-case
switch
语句可以认为是一个加强版的 if
语句。if else
语句通过一个 switch
和多个 case
语句实现。但是两者之间也是有区别的,接下来就让我们举几个例子。
switch any expression of type T {
case any expression of same type T: { code to be executed if the case expression is equal to the switch expression }
case any expression of same type T: { code to be executed if this case expression is equal to the switch expression }
//any number of case statements are allowed
default: { code to be executed if none of the case expressions match the switch expression }
}
注意以下几点
switch
和case
中对应的比较变量类型应该相同。比如,switch
中使用int
而case
中的表达式变量为string
,编译时会产生错误。- 如果在
switch
中没有任何表达式,那么默认的类型为bool
- 如果多个
case
语句都满足关系,将会执行遇到的第一个case
语句 - 和其它语言不同,每一个
case block
都是独立的,代码不会继续fall through
(译者注:即不用break
)(每一个case
块就相当于一个if-else
块,可以使用fallthrough
关键字,显示的要求代码可以向下执行) - 如果所有的
case
都不满足,那么default
将会执行 case
语句中可以含有表达式- 每个
case
块的{}
是可选的 default
块也是可选的- 任意数量的
case
块都是可行的——甚至没有case
块也是可以滴,虽然没啥卵用 - 允许一个
case
语句中有多个表达式,通过,
分割 default
块可以放在switch
块的任何地方
switch
无表达式时默认为 bool
类型
在以下的代码中,switch
中没有任何表达式,则默认使用 bool
类型。在 case
语句中,使用 true
和 false
进行判断,当然 true
语句块会执行,其它语句块都不会执行。
package main
import "fmt"
func main() {
switch {
case true: fmt.Println("first is true")
case false: fmt.Println("second is false")
default: fmt.Println("default")
}
}
first is true
switch
和 case
对应的类型必须相同
在下面代码中, switch
的值为 int
类型,case
语句的类型也必须为 int
类型。注释部分使用的是 i > 7
,由于是 bool
类型,故而会产生编译错误。
package main
import "fmt"
func main() {
i := 5
switch i {
case 4: fmt.Println("number 4")
case 5:fmt.Println("number 5")
case 6: fmt.Println("number 6")
//case i>7: fmt.Println("is > 7") //will be compile error as type int and bool don't match between case and switch
default: fmt.Println("default")
}
}
number 5
多个表达式通过 ,
分割
在下面的代码中,判定某个值是奇数还是偶数。由于多个值都可以满足同一个条件,而又不想写多个相同的代码,所以可以通过单个 case
语句中通过 ,
分割多个表达式实现。
package main
import "fmt"
func main() {
j := 4
switch j {
case 1,3,5,7,9: fmt.Println(j, "is odd")
case 0,2,4,6,8: fmt.Println(j, "is even")
default: fmt.Println(j, "is not an integer between 0 and 9")
}
}
4 is even
字符串测试
package main
import "fmt"
func main() {
s1 := "abcd"
s2 := "efgh"
switch s1 {
case s2: fmt.Println("the two strings are equal")
default: fmt.Println("the two strings are NOT equal") //since nothing else matches, the default block is executed
}
}
the two strings are NOT equal
fallthrough 语句
在其它一些语言中,例如 C
和 Java
,switch-case
语句执行时,所有的 case
语句块都会依次执行,除非显示的通过 break
语句终止。但是在 Go
中,则刚好相反。如果想要继续执行下面的 case
块,需要使用 fallthrough
关键字。
package main
import "fmt"
func main() {
k := 6
switch k {
case 4: fmt.Println("was <= 4"); fallthrough;
case 5: fmt.Println("was <= 5"); fallthrough;
case 6: fmt.Println("was <= 6"); fallthrough;
case 7: fmt.Println("was <= 7"); fallthrough;
case 8: fmt.Println("was <= 8"); fallthrough;
default: fmt.Println("default case")
}
}
was <= 6
was <= 7
was <= 8
default case
Golang一种神奇的语言,让我们一起进步