如何通过接口获取指针的值类型?

bel*_*nta 5 go

这个操场说明了我的问题.

基本上我有一个接受空接口作为参数的函数.我想传递任何内容并打印有关类型和值的信息.

它按预期工作,除非我将指针传递给自定义类型(在我的示例中,基础结构类型).我不完全确定反射模型在那时是如何构建的.由于函数签名interface{}在我调用时指定了一个参数,reflect.Indirect(v).Kind()它自然会返回,interface但我想知道函数被调用时的类型.

以下是来自游乐场的相同代码:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var s interface{}
    s = CustomStruct{}

    PrintReflectionInfo(s)
    PrintReflectionInfo(&s)
}

type CustomStruct struct {}

func PrintReflectionInfo(v interface{}) {
    // expect CustomStruct if non pointer
    fmt.Println("Actual type is:", reflect.TypeOf(v))

    // expect struct if non pointer
    fmt.Println("Value type is:", reflect.ValueOf(v).Kind())

    if reflect.ValueOf(v).Kind() == reflect.Ptr {
        // expect: CustomStruct
        fmt.Println("Indirect type is:", reflect.Indirect(reflect.ValueOf(v)).Kind()) // prints interface

        // expect: struct
        fmt.Println("Indirect value type is:", reflect.Indirect(reflect.ValueOf(v)).Kind()) // prints interface
    }

    fmt.Println("")
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 11

要获取struct值,您需要获取接口值的元素:

fmt.Println("Indirect type is:", reflect.Indirect(reflect.ValueOf(v)).Elem().Type()) // prints main.CustomStruct

fmt.Println("Indirect value type is:", reflect.Indirect(reflect.ValueOf(v)).Elem().Kind()) // prints struct
Run Code Online (Sandbox Code Playgroud)

操场的例子

此代码有助于理解示例中的类型:

rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
    fmt.Println(rv.Kind(), rv.Type())
    rv = rv.Elem()
}
fmt.Println(rv.Kind(), rv.Type())
Run Code Online (Sandbox Code Playgroud)

输出&s是:

ptr *interface {}
interface interface {}
struct main.CustomStruct
Run Code Online (Sandbox Code Playgroud)

操场的例子