简体   繁体   English

如何使用反射获得自定义类型?

[英]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?有没有办法通过反射从RealStatus类型到Status类型?

Yes, it's possible if you mean to get a Status value from a RealStatus value using reflection;是的,如果您想使用反射从RealStatus值中获取Status,这是可能的; you may use Value.Convert() for that, for example:您可以Value.Convert()使用Value.Convert() ,例如:

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 ):这将输出(在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 .请注意,您只能从反射中获取interface{}值,因此要将其用作Status值,您仍然需要一个类型断言 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 .输出相同(在Go Playground上尝试),并且它的优点是s具有静态类型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 . RealStatusStatus类型之间的唯一关系是它们共享相同的基础类型int

It is possible to convert between values of those types as shown in the answer by @icza.如@icza 的回答所示,可以在这些类型的值之间进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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