使用 Reflect 获取自定义类型的基类型
Getting the base type of a custom type using Reflect
假设我在 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")
}
这会打印“不是 timeType”。我想做的是找到一种方法来查看自定义类型使用的 base 类型(即 type CustomType time.Time
中的 time.Time
)是否属于类型time.Time
.
我试过使用 reflect 的 Kind()
函数,但是 returns struct
因为 time.Time
是一个结构。
这是一个 playground 代码。
你不能完全这样,因为这不是类型在 Go 中的工作方式。在您的示例中,CustomTime
的基础类型 不是时间 ; CustomTime
和 time.Time
共享相同的底层类型,即 struct
类型。 From the docs:
Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.
这意味着 CustomTime
的底层类型不是 time.Time
,它是 time.Time
的 底层类型。
您可以使用 reflect.Type
's ConvertibleTo()
method 来查看一种类型是否可以转换为另一种类型,这与您所描述的尽可能接近。
假设我在 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")
}
这会打印“不是 timeType”。我想做的是找到一种方法来查看自定义类型使用的 base 类型(即 type CustomType time.Time
中的 time.Time
)是否属于类型time.Time
.
我试过使用 reflect 的 Kind()
函数,但是 returns struct
因为 time.Time
是一个结构。
这是一个 playground 代码。
你不能完全这样,因为这不是类型在 Go 中的工作方式。在您的示例中,CustomTime
的基础类型 不是时间 ; CustomTime
和 time.Time
共享相同的底层类型,即 struct
类型。 From the docs:
Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.
这意味着 CustomTime
的底层类型不是 time.Time
,它是 time.Time
的 底层类型。
您可以使用 reflect.Type
's ConvertibleTo()
method 来查看一种类型是否可以转换为另一种类型,这与您所描述的尽可能接近。