Go基础-类型开关(Type Switch)

 使用类型开关(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)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值