Go类型选择
类型选择(type switch)是处理接口多种可能类型的便捷方式。
type switch语法
基本语法
Go
var i interface{} = "hello"
switch v := i.(type) {
case string:
fmt.Println("字符串:", v)
case int:
fmt.Println("整数:", v)
case bool:
fmt.Println("布尔:", v)
default:
fmt.Println("未知类型:", v)
}
type switch中v是具体类型的值,在每个case中类型确定。
无值类型选择
Go
switch i.(type) {
case string:
fmt.Println("是字符串")
case int:
fmt.Println("是整数")
default:
fmt.Println("其他类型")
}
类型选择示例
处理多种输入类型
Go
func process(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println("整数:", v, "平方:", v*v)
case string:
fmt.Println("字符串:", v, "长度:", len(v))
case []int:
fmt.Println("整数slice:", v)
case map[string]int:
fmt.Println("map:", v)
default:
fmt.Printf("未知类型: %T\n", v)
}
}
process(42) // 整数: 42 平方: 1764
process("hello") // 字符串: hello 长度: 5
process([]int{1,2}) // 整数slice: [1 2]
自定义类型判断
Go
type User struct {
Name string
Age int
}
func handle(v interface{}) {
switch v := v.(type) {
case User:
fmt.Println("User:", v.Name, v.Age)
case *User:
fmt.Println("User指针:", v.Name, v.Age)
default:
fmt.Println("非User类型")
}
}
nil类型处理
Go
switch v := i.(type) {
case nil:
fmt.Println("nil值")
case string:
fmt.Println("字符串:", v)
default:
fmt.Println("其他")
}
nil是一个特殊的case,用于处理接口值为nil的情况。
多类型分支
Go
switch v := i.(type) {
case int, int32, int64:
fmt.Println("整数类型:", v)
case float32, float64:
fmt.Println("浮点类型:", v)
case string:
fmt.Println("字符串:", v)
default:
fmt.Println("其他")
}
多类型合并时,v在该case中为interface{}类型。
type switch vs 类型断言
| 特性 | type switch | 类型断言 |
|---|---|---|
| 处理类型 | 多种类型 | 单一类型 |
| 语法 | switch i.(type) | i.(T) |
| 类型检查 | 自动匹配case | 手动判断 |
| 获取值 | 每case自动转换 | 需ok判断 |
| 适用场景 | 多类型分支 | 单类型检查 |
类型断言处理多类型对比
Go
// 类型断言方式(繁琐)
if v, ok := i.(int); ok {
fmt.Println("int:", v)
} else if v, ok := i.(string); ok {
fmt.Println("string:", v)
} else {
fmt.Println("其他")
}
// type switch方式(简洁)
switch v := i.(type) {
case int:
fmt.Println("int:", v)
case string:
fmt.Println("string:", v)
default:
fmt.Println("其他")
}
要点总结
- type switch用
i.(type)判断类型 - case中v自动转换为具体类型值
- nil case处理接口为nil的情况
- 多类型合并用逗号分隔
- type switch比多个断言更简洁
- default处理未匹配类型
- 无值type switch只判断类型不获取值
📝 发现内容有误?点击此处直接编辑