a :=1switch a {case1: fmt.Printf("case 1\n")fallthroughcase2: fmt.Printf("caes 2\n")}// case 1// caes 2
字符串switch
Go语言的switch比C++和Java这类语言的更灵活。
我们可以基于字符串做switch:
s := "foo"
switch s {
case "foo":
fmt.Printf("s is 'foo'\n")
case "bar":
fmt.Printf("s is 'bar'\n")
}
// s is 'foo'
空switch表达式
当case语句后面都是布尔表达式时,switch语句后面的表达式可以为空,而不止是常量。
func check(n int) {
switch {
case n > 0 && n%3 == 0:
fmt.Printf("n is %d, divisible by 3\n", n)
case n >= 4:
fmt.Printf("n is %d (>= 4)\n", n)
default:
fmt.Printf("default: n is %d\n", n)
}
}
check(3)
check(4)
check(6)
check(1)
n is 3, divisible by 3
n is 4 (>= 4)
n is 6, divisible by 3
default: n is 1
Program exited.
case的求值顺序
如果多个case语句后面的表达式求值都为true,会发生什么?
例如上面的例子中,n=6时,既满足n > 0 && n%3 == 0,也满足n >= 4。
正如你所见,只有一个case会被执行,最先定义的那个。
switch语句中赋值
switch n := rand.Intn(9); n {
case 1, 2, 3:
fmt.Printf("case 1, 2, 3: n is %d\n", n)
case 4, 5:
fmt.Printf("case 4, 5: n is %d\n", n)
default:
fmt.Printf("default: n is %d\n", n)
}
类型switch
如果变量是interface类型的,您还可以基于它的底层类型进行switch:
package main
import "fmt"
func printType(iv interface{}) {
// inside case statements, v is of type matching case type
switch v := iv.(type) {
case int:
fmt.Printf("'%d' is of type int\n", v)
case string:
fmt.Printf("'%s' is of type string\n", v)
case float64:
fmt.Printf("'%f' is of type float64\n", v)
default:
fmt.Printf("We don't support type '%T'\n", v)
}
}
func main() {
printType("5")
printType(4)
printType(true)
}