![](/img/trans.png)
[英]How do I use type switch on struct fields (when field is of interface type)?
[英]How do I use reflect to check if the type of a struct field is interface{}?
我正在使用reflect包来确定struct字段的类型是interface{}
我想像这样进行比较(其中t
是reflect.Type
):
if t == reflect.TypeOf(interface{}) {
}
问题是编译器抱怨: type interface {} is not an expression
。
无论如何都要检查结构字段的类型是否是interface{}
?
您可以通过创建nil实例并使用反射来获取接口Y
的类型:
yType := reflect.TypeOf((*Y)(nil)).Elem()
然后使用表达式
reflect.TypeOf(x).Implements(yType)
检查类型是否实现了接口。
接口本身无法实例化。 作为空接口的接口{}接口由所有类型实现,因此所有字段都实现该接口。
https://play.golang.org/p/gRfheIW_9Y
实际上它也适用于空接口{}本身,但这将始终返回true(如果我没有遗漏某些东西):
interface{}
是一个类型,而reflect.TypeOf()
需要一个值。 所以你不能将文字interface{}
传递给它。 您只能传递一个值。
回到原来的问题。 让我们看一个struct
示例:
type My struct {
A int
B interface{}
C io.Reader
}
您想知道字段的类型是否为interface{}
。 获取struct
类型的reflect.Type
,然后可以使用Type.Field()
或Type.FieldByName()
访问字段。
这将为您提供一个类型为reflect.StructField
的值,该值存储字段的类型。
到现在为止还挺好。 但是我们应该将它与什么进行比较? interface{}
是一个包含0个方法的接口类型。 您不能拥有(实例化)该类型的值。 您只能拥有具体类型的值,但是,它们可能包含在接口类型中。
您可以使用Type.Kind
,并将其与reflect.Interface
进行比较,它会告诉您它是否是一个接口,但对于所有接口类型都是true
。 您还可以检查它是否有0个方法使用Type.NumMethod()
,对于interface{}
必须为0,但其他接口也可以有0个方法...
您可以使用Type.Name
,但由于interface{}
是未命名的类型,因此其名称为空字符串""
(还有其他未命名的类型)。 您可以使用Type.String()
为空接口返回"interface {}"
:
t := reflect.TypeOf(My{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("Field %q, type: %-12v, type name: %-8q, is interface{}: %v\n",
f.Name, f.Type,
f.Type.Name(),
f.Type.String() == "interface {}",
)
}
输出(在Go Playground上试试):
Field "A", type: int , type name: "int" , is interface{}: false
Field "B", type: interface {}, type name: "" , is interface{}: true
Field "C", type: io.Reader , type name: "Reader", is interface{}: false
您可能会发现此相关问题有趣/有用: 使用反射识别非内置类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.