如何获得接口的反射类型? [英] How to get the reflect.Type of an interface?

查看:281
本文介绍了如何获得接口的反射类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了确定给定类型是否使用反射包实现了一个接口,您需要传递reflect.Type来反射.Type.Implements()。如何获得这些类型之一?



例如,尝试获取未初始化的os.Error(接口)类型的类型不是 (它会在你调用Kind()时发生混乱)

  var err os.Error 
fmt .Printf(%#v \ n,reflect.TypeOf(err).Kind())




  var err * os.Error $ b 

解决方案

bt:= reflect.TypeOf(err).Elem()

或者在一行中:

  t:= reflect.TypeOf((* os.Error)(nil))。Elem()


In order to determine whether a given type implements an interface using the reflect package, you need to pass a reflect.Type to reflect.Type.Implements(). How do you get one of those types?

As an example, trying to get the type of an uninitialized os.Error (interface) type does not work (it panics when you to call Kind() on it)

var err os.Error
fmt.Printf("%#v\n", reflect.TypeOf(err).Kind())

解决方案

Do it like this:

var err *os.Error
t := reflect.TypeOf(err).Elem()

Or in one line:

t := reflect.TypeOf((*os.Error)(nil)).Elem()

这篇关于如何获得接口的反射类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆