Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

go - Getting the base type of a custom type using Reflect

Say I create a custom type in Go:

type CustomTime time.Time

Using reflection, I'm comparing types, e.g.

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 (i.e. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 CustomTimes 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...