Go 使用Reflect获取自定义类型的基类型

Go 使用Reflect获取自定义类型的基类型,go,reflection,types,Go,Reflection,Types,假设我在Go中创建自定义类型: type CustomTime time.Time 使用反射,我比较类型,例如 var foo CustomTime = CustomTime(time.Now()) customType := reflect.TypeOf(foo) timeType := reflect.TypeOf(time.Now()) if customType == timeType { fmt.Println("Is timeType") } els

假设我在Go中创建自定义类型:

type CustomTime time.Time
使用反射,我比较类型,例如

var foo CustomTime = CustomTime(time.Now())
customType := reflect.TypeOf(foo)

timeType := reflect.TypeOf(time.Now())

if customType == timeType {
    fmt.Println("Is timeType")
} else {
    fmt.Println("Is not timeType")
}
此打印“不是时间类型”。我想做的是找到一种方法来查看自定义类型使用的基本类型(即
类型CustomType time.time中的
时间
)是否为
时间
类型

我尝试过使用reflect的
Kind()
函数,但这两个函数都返回
struct
,因为
time.time
是一个struct


下面是一个关于这段代码的例子。

您不能确切地说,因为Go中的类型不是这样工作的。在您的示例中,
CustomTime
的底层类型不是Time;
CustomTime
time.time
都共享相同的基础类型,即
struct
类型:

每个类型T都有一个底层类型:如果T是预先声明的布尔、数值或字符串类型之一,或者是类型文字,则相应的底层类型是T本身。否则,T的基础类型是T在其类型声明中引用的类型的基础类型

这意味着
CustomTime
s的底层类型不是
time.time
,而是
time.time
的底层类型


您可以使用查看一种类型是否可转换为另一种类型,这与您所描述的内容尽可能接近。

您无法使用reflect软件包从CustomTime获取时间。CustomTime和time.time共享相同的基础类型,但其他类型之间没有关系。Go没有“基本”类型的概念。为什么要使用反射?为什么不是一个简单的类型断言或类型开关呢?谢谢你提供的信息。
reflect.AssignableTo()
reflect.ConvertableTo()
之间的功能区别是什么?在这种情况下,哪一个更好?@Jordan,这取决于你的目标。这两个方法都不会告诉您两个类型是否共享相同的基础类型。两个类型可以共享相同的基础类型,并且不可分配(例如time.time和CustomTime)。两种类型可以转换,但不能共享相同的下划线类型(例如byte和int)。ConvertableTo是为您的两种类型返回true的方法。很抱歉,您是对的,
ConvertableTo
是本例中正确的方法。更新。