产品展示
  • 适用于荣威RX5名爵GS锐腾 暖风电机 空调翻板 风门 翻板 蒸发箱
  • NFA纽福克斯12V 25A全自动汽车电瓶充电器蓄电池充电机 引擎启动
  • 天津一汽骏派A50/D60/CX65夏利N5威志V5原装瓦尔塔蓄电池汽车电瓶
  • 大众新款宝来速腾高尔夫老款捷达朗逸1.6L原装蓄电池60AH汽车电瓶
  • 汽车贴纸猫和老鼠可爱卡通车贴车门个性创意装饰划痕遮挡立体车贴
联系方式

邮箱:admin@aa.com

电话:020-123456789

传真:020-123456789

汽车配件

2.9 Go语言中的Switch

2024-05-02 10:40:26      点击:449

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}

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

  • • 函数的定义方法
  • • 定义了一个map ,但是值的类型为空接口 ,意思就是可以是任何类型的值 ,这在接口章节还会详细讲解 ,所以大家看到这里不要纠结,继续往下看
  • • 赋值时,特意给value不同的类型, string/int/float类型

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

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

阴阳师金鱼姬什么时候出 金鱼姬上线时间
洛克王国栀子花印章有什么用