获取基于原始类型的类型的reflect.Kind

Max*_*man 2 reflection interface go

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

对此问题的另一种答案可能是如何在调用 Kind() 时获取返回reflect.Interfaces 的任何类型的reflect.Type。

这是Go Playground上的完整示例:

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())
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

reflect.TypeOf()(和reflect.ValueOf()) 期望一个interface{}. 基本上,无论您传递给 的值是什么reflect.TypeOf(),如果它还不是接口值,它将被interface{}隐式包装在一个接口值中。如果传递的值已经是一个接口值,那么存储在其中的具体值将作为interface{}.

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

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

例子:

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

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

fmt.Println(t.Kind())
Run Code Online (Sandbox Code Playgroud)

哪个输出(在Go Playground上尝试):

test
main.ID
interface
Run Code Online (Sandbox Code Playgroud)

请参阅相关问题:What is the Difference betweenreflect.ValueOf() and Value.Elem() in go?