switch语句
简单的switch
语句:
a := 1
switch a {
case 1, 3:
fmt.Printf("a is 1 or 3\n")
case 2:
fmt.Printf("a is 2\n")
default:
fmt.Printf("default: a is %d\n", a)
}
注意,一个case
后面可以跟多个值。如上例的1和 3。
落空(fallthrough)
跟其他大多数语言(如Java或C++)不同,您不需要在一个case
之后放置break
语句来阻止接下来的case
的继续执行。
这种默认行为是缺陷(Bug)的常见来源。
相反,您可以在Go中使用fallthrough
语句来达成上述行为。
a := 1
switch a {
case 1:
fmt.Printf("case 1\n")
fallthrough
case 2:
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)
case
的求值顺序
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)
}
最后更新于
这有帮助吗?