简体   繁体   中英

How can I get custom type with reflect?

The following data types are defined:

type Status int
type RealStatus Status

Is there a way to get from RealStatus type to Status type with reflection?

Yes, it's possible if you mean to get a Status value from a RealStatus value using reflection; you may use Value.Convert() for that, for example:

type Status int
type RealStatus Status

rs := RealStatus(1)

st := reflect.TypeOf(Status(0))

var i interface{}
i = reflect.ValueOf(rs).Convert(st).Interface()

fmt.Printf("%T %v", i, i)

This will output (try it on the Go Playground ):

main.Status 1

Note that you can only get an interface{} value from reflection, so to use it as a Status value, you still need a type assertion . Given that, you could just use a simple type conversion in the first place, like in this example:

rs := RealStatus(1)

var s Status
s = Status(rs)

fmt.Printf("%T %v", s, s)

Which outputs the same (try it on the Go Playground ), and it has the advantage that s has static type Status .

No, it is not possible to get one type from the other. The only relationship between RealStatus and Status types is that they share the same underlying type int .

It is possible to convert between values of those types as shown in the answer by @icza.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM