2.9 Go语言中的Switch     DATE: 2024-04-28 01:47:30

2.9 Go语言中的Switch

基本语法

在讲述if-else时已经提到,如果有多个判断条件 ,Go语言中提供了Switch-Case的方式。如果switch后面不带条件相当于switch true

// Convert hexadecimal character to an int valuen switch { n case '0' <= c && c <= '9':n return c - '0'n case 'a' <= c && c <= 'f':n return c - 'a' + 10n case 'A' <= c && c <= 'F':n return c - 'A' + 10n }n return 0

fallthrough使用方法

默认情况下,case满足执行后会进行break  ,后面case即使满足条件也不再循环 ,如果想继续执行,则需要添加fallthrough ,

package mainnnimport "fmt"nnfunc main() { n i := 3n switch i { n case i > 0:n fmt.Println("condition 1 triggered")n fallthroughn case i > 2:n fmt.Println("condition 2 triggered")n fallthroughn default:n fmt.Println("Default triggered")n }n}n

此时所有的case都会被执行

condition 1 triggeredncondition 2 triggerednDefault triggered

多条件匹配

如果同一个条件满足 ,也可以这样罗列到同一条件,相当于或条件

switch i { n case 0, 1:n f()n default:n g()n}

判断接口(interface)类型

空接口

后面我们会讲到接口 ,通过switch可以对type进行判断,获取接口的真实类型 。

package mainn nimport "fmt"n nfunc main() { n var value interface{ }n switch q:= value.(type) { n case bool:n fmt.Println("value is of boolean type")n case float64:n fmt.Println("value is of float64 type")n case int:n fmt.Println("value is of int type")n default:n fmt.Printf("value is of type: %T", q)n }n}n

在上面的例子中,我们定义了一个空接口

var value interface{ }

同时使用switch来判断类型

switch q:= value.(type) {

由于空接口没有内容,所以类型为nil ,触发了default

value is of type: <nil>

获取实际类型

我们对上面的例子进行改造,同时让空接口拥有实际的值,再来看看执行的效果

package mainnnimport "fmt"nnfunc valueType(i interface{ }) { n switch q:= i.(type) { n case bool:n fmt.Println("value is of boolean type")n case float64:n fmt.Println("value is of float64 type")n case int:n fmt.Println("value is of int type")n default:n fmt.Printf("value is of type: %Tn", q)nn }n}nnfunc main() { n person := make(map[string]interface{ }, 0)nn person["name"] = "Alice"n person["age"] = 21n person["height"] = 167.64nn fmt.Printf("%+vn", person)nn for _, value := range person { n valueType(value)n }n}

这里有几个还没有讲到的知识点:

最后通过循环将变量传给valueType函数,看看程序输出什么结果

map[age:21 height:167.64 name:Alice]nvalue is of type: stringnvalue is of int typenvalue is of float64 type