Say I create a custom type in Go:
type CustomTime time.Time
Using reflection, I'm comparing types, eg
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")
}
This prints "Is not timeType". What I'm trying to do is find a way to see if the base type that the custom type uses (ie the time.Time
in type CustomType time.Time
) is of type time.Time
.
I've tried using reflect's Kind()
function, but that returns struct
for both since time.Time
is a struct.
Here's a playground with this code.
You can't exactly, because that's not how types work in Go. In your example, CustomTime
's underlying type isn't Time ; both CustomTime
and time.Time
share the same underlying type, which is a struct
type. 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.
That means that CustomTime
s underlying type isn't time.Time
, it's time.Time
's underlying type .
You can use reflect.Type
's ConvertibleTo()
method to see if one type is convertible to another, which is as close as you're likely to get to what you're describing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.