产品展示
  • 长城哈弗M1M4H1H2H5H6H7汽车同轴喇叭音响全频6.5寸改装重低音炮
  • 骆驼DF蓄电池12V80AH皮卡越野农用货车船挂机叉车1D汽车电瓶95D31
  • 【漫步者汽车音响】超重车载10寸无源低音炮CW10发烧级HIFI震撼级
  • 大众朗逸plus水杯垫汽车用品内饰装饰22款2022车内改装配件专用21
  • 特价 车声派 汽车功放汽车音响大功率2声道二路车载低音炮功放机
联系方式

邮箱:admin@aa.com

电话:020-123456789

传真:020-123456789

产品中心

2.9 Go语言中的Switch

2024-05-03 05:53:27      点击:994

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

魔兽世界怀旧服圣骑士练级天赋攻略
王者荣耀 s22赛季已正式上线 停机大版本更新内容详解汇总分享