常见go语言的两个switch-case用法
1 简介
Go语言中的switch语句是一个强大的工具,可以比一系列if-else语句更高效地处理多个条件。它允许您将一个变量与多个值进行比较,并根据匹配执行不同的代码块。
switch 语句用于基于不同条件执行不同动作。每个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止。
value/type switch在 Go 里,switch 有两种常见用法:
值匹配 switch
类型匹配 switch(type switch)
最基本示例
day := "Tuesday"
switch day {
case "Monday":
fmt.Println("Start of the work week")
case "Tuesday":
fmt.Println("Second day of the work week")
case "Wednesday", "Thursday":
fmt.Println("Midweek")
case "Friday":
fmt.Println("End of the work week")
default:
fmt.Println("Weekend")
}
以上day 与每个周名进行匹配,完全大小写匹配后输出对应case的打印。
2 类型匹配
语法1:switch x.(type) { … }
switch x.(type) {
case int:
fmt.Println("int")
case string:
fmt.Println("string")
case contact:
fmt.Println("contact")
default:
fmt.Println("unknown")
}
这里的 x.(type) 只能用于 type switch,意思是“查看接口变量 x 的具体底层类型”。
注意:x 必须是接口类型(比如 interface{} 或 any),否则编译报错。
在 case 里,你只能根据类型做分支,而不能直接使用具体值。
语法2:switch newType := x.(type) { … }
switch newType := x.(type) {
case int:
fmt.Printf("int: %d\n", newType) // newType 是 int 类型
case string:
fmt.Printf("string: %s\n", newType) // newType 是 string 类型
case contact:
fmt.Printf("contact: %+v\n", newType) // newType 是 contact 类型
default:
fmt.Println("unknown")
}
区别在于:
在 switch x.(type) 中,x 保持接口类型,case 分支里无法直接使用具体类型的值。
在 switch newType := x.(type) 中,分支会把 newType 绑定为对应 case 的具体类型,这样就可以直接用 newType 做操作。
示例如:
var x any = "hello"
switch v := x.(type) {
case int:
fmt.Println(v + 1) // v 是 int
case string:
fmt.Println(v + "!") // v 是 string
}
3 普通值 switch:switch “Mhi” { … }
switch "Dhi" {
case "Daniel":
fmt.Println("Wassup Daniel")
case "Dedhi":
fmt.Println("Wassup Dedhi")
case "Jenny":
fmt.Println("Wassup Jenny")
default:
fmt.Println("Have you no friends?")
}
执行逻辑
switch “Mhi” 代表:拿 “Mhi” 这个值去和每个 case 的值做 相等匹配。
它会顺序检查:
“Dhi” == “Daniel” → false
“Dhi” == “Medhi” → false
“Dhi” == “Jenny” → false
都不相等,于是进入 default,输出:
Have you no friends?
关于 “Dhi”
在 case 里 “Dedhi” 少了个 e,所以和 “Dhi” 根本不相等。
这其实说明 Go 的 switch case 是完全精确匹配(区分大小写和字符),并不像某些语言里会做模糊或部分匹配。
相等 的例子:
switch "Dedhi" {
case "Dedhi":
fmt.Println("Wassup Medhi")
}
就能正确输出 “Wassup Medhi”。
4 总结:
switch x.(type) 只能用于接口,检查底层类型。
switch newType := x.(type) 可以直接获得转换后的具体类型值,方便操作。
普通 switch value 是逐个 case 值比较(完全匹配),“Mhi” 在例子里不匹配任何 case,因此走 default。
- 点赞
- 收藏
- 关注作者
评论(0)