You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对reflect.TypeOf(value)的返回值使用类型switch语句?

如何对reflect.TypeOf的返回值使用类型switch语句

你写的这段代码达不到预期效果——因为reflect.TypeOf(value)返回的是reflect.Type类型的对象,不是你定义的int类型本身。直接对t做类型断言switch tv := t.(type)去匹配int根本不会命中,毕竟t的实际类型是reflect.Type,跟int完全是两回事。

下面给你两种正确的实现方式:

用Kind()判断基础类型种类

reflect.Type有个Kind()方法,能返回表示类型基础种类的枚举值(比如int、string、slice这些),针对这个值做switch就对了:

import (
    "fmt"
    "reflect"
)

func main() {
    var value int = 123
    t := reflect.TypeOf(value)
    switch t.Kind() {
    case reflect.Int:
        fmt.Println("type: INT")
    case reflect.String:
        fmt.Println("type: STRING")
    // 其他基础类型都可以按这个方式加case
    }
    fmt.Println(t)
}

精确匹配具体类型(包括自定义类型)

如果要区分像int和int32这种同基础类型但不同具体类型的情况,或者自定义类型,直接把t和目标类型的反射类型做比较就行:

import (
    "fmt"
    "reflect"
)

type MyInt int

func main() {
    var value MyInt = 123
    t := reflect.TypeOf(value)
    switch {
    case t == reflect.TypeOf(int(0)):
        fmt.Println("type: int")
    case t == reflect.TypeOf(MyInt(0)):
        fmt.Println("type: MyInt")
    case t == reflect.TypeOf(""):
        fmt.Println("type: string")
    }
    fmt.Println(t)
}

简单说,第一种方法看的是“类型大类”,自定义类型MyInt和int的Kind是一样的;第二种方法能精准识别每个不同的类型,包括你自己定义的类型。

内容的提问来源于stack exchange,提问作者clarkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:09:55