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语句后面的表达式可以为空,而不止是常量。
funccheck(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 {case1, 2, 3: fmt.Printf("case 1, 2, 3: n is %d\n", n)case4, 5: fmt.Printf("case 4, 5: n is %d\n", n)default: fmt.Printf("default: n is %d\n", n)}
类型switch
如果变量是interface类型的,您还可以基于它的底层类型进行switch:
packagemainimport"fmt"funcprintType(iv interface{}) {// inside case statements, v is of type matching case typeswitch v := iv.(type) {caseint: fmt.Printf("'%d' is of type int\n", v)casestring: fmt.Printf("'%s' is of type string\n", v)casefloat64: fmt.Printf("'%f' is of type float64\n", v)default: fmt.Printf("We don't support type '%T'\n", v) }}funcmain() {printType("5")printType(4)printType(true)}