使用类型开关(Type Switch)在运行时检查变量类型
一、类型开关(Type Switch)基础语法
func checkType(x interface{}) {
switch x.(type) { // 固定语法,type是关键字
case int:
fmt.Println("int类型")
case string:
fmt.Println("string类型")
case bool:
fmt.Println("bool类型")
default:
fmt.Println("未知类型")
}
}
二、完整使用示例
1. 基本类型检查
func printType(v interface{}) {
switch t := v.(type) { // 将类型赋值给变量t
case int:
fmt.Printf("Type int: %d\n", t) // t已是int类型
case float64:
fmt.Printf("Type float64: %f\n", t)
case string:
fmt.Printf("Type string: %q\n", t)
case bool:
fmt.Printf("Type bool: %v\n", t)
default:
fmt.Printf("Unexpected type %T\n", t) // %T打印实际类型
}
}
// 使用示例
printType(42) // Type int: 42
printType("hello") // Type string: "hello"
printType(3.14) // Type float64: 3.140000
printType(make(chan int)) // Unexpected type chan int
2. 复合类型检查
func checkComplexType(v interface{}) {
switch t := v.(type) {
case []int:
fmt.Println("int切片,长度:", len(t))
case map[string]int:
fmt.Println("string->int映射,键数:", len(t))
case func(int) int:
fmt.Println("函数类型,调用结果:", t(10))
default:
fmt.Println("不支持的类型")
}
}
三、高级用法
1. 多类型合并判断
func checkNumber(v interface{}) {
switch v.(type) {
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64:
fmt.Println("数字类型")
default:
fmt.Println("非数字类型")
}
}
2. 带初始化语句的类型开关
func process(v interface{}) {
switch val := v.(type) { // 可同时获取值和类型
case string:
fmt.Println("字符串处理:", strings.ToUpper(val))
case int:
fmt.Println("数字平方:", val*val)
}
}
3. 嵌套类型检查
func deepCheck(v interface{}) {
switch t := v.(type) {
case interface{ Read([]byte) (int, error) }: // 检查接口实现
fmt.Println("实现了io.Reader")
case struct{ id int }:
fmt.Println("匿名结构体,id=", t.id)
}
}