获取基于原始类型的类型的reflect.Kind [英] Get the reflect.Kind of a type which is based on a primitive type

查看:57
本文介绍了获取基于原始类型的类型的reflect.Kind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个reflect.Kind作为一个reflect.Interface,用于实现接口但其实现基于原始类型的类型: type id string

I would like to get the reflect.Kind as a reflect.Interface for a type which implements an interface but where its implementation is based on a primitive type: type id string

对此的另一种选择可能是如何获取任何种类的reflect.Type,在调用Kind()时返回reflect.Interfaces.

An alternative answer for this could be how to get any kind of reflect.Type that returns reflect.Interfaces when calling Kind().

这是游乐场:

type ID interface {
    myid()
}

type id string

func (id) myid() {}

func main() {
    id := ID(id("test"))
    
    fmt.Println(id)
    fmt.Println(reflect.TypeOf(id))
    
    // How to get the kind to return "reflect.Interface" from the var "id"?
    fmt.Println(reflect.TypeOf(id).Kind())
}

推荐答案

reflect.TypeOf() (以及 reflect.ValueOf()> )需要一个界面{} .基本上,无论您传递给 reflect.TypeOf()的值是什么,如果它还不是接口值,它将被隐式包装在 interface {} 中.如果传递的值已经是接口值,则存储在其中的具体值将作为 interface {} 传递.

reflect.TypeOf() (and reflect.ValueOf()) expects an interface{}. Basically whatever value you pass to reflect.TypeOf(), if it's not already an interface value, it will be wrapped in an interface{} implicitly. If the passed value is already an interface value, then the concrete value stored in it will be passed as a interface{}.

为了避免这种重新打包",这是当指向接口的指针有意义时的罕见情况之一,实际上,您在这里无法避免.您必须传递一个指向接口值的指针.

In order to avoid this "repacking", this is one of those rare cases when a pointer to interface makes sense, in fact you can't avoid it here. You have to pass a pointer to the interface value.

因此,如果您将指针传递给interface,则该指针将被包装在 interface {} 值中.您可以使用 Type.Elem()来获取指向类型"的类型描述符:即指针类型的元素类型,它将是您所使用的接口类型的类型描述符正在寻找.

So if you pass a pointer to interface, this pointer will be wrapped in an interface{} value. You may use Type.Elem() to get the type descriptor of the "pointed type": that is, the element type of the pointer type, which will be the type descriptor of the interface type you're looking for.

示例:

id := ID(id("test"))

fmt.Println(id)
t := reflect.TypeOf(&id).Elem()
fmt.Println(t)

fmt.Println(t.Kind())

哪些输出(在进入游乐场上尝试)

test
main.ID
interface

请参阅相关问题: 查看全文

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