douyingtai6662 2016-01-31 04:32
浏览 72
已采纳

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

This playground illustrates my question.

Basically I have a function that accepts an empty interface as argument. I want to pass anything in and print information on the types and values.

It works as expected except when I pass a pointer to a custom type (in my example, of underlying struct type). I am not entirely sure how the reflection model is structured at that point. Since the function signature specifies an interface{} argument when I call reflect.Indirect(v).Kind() it naturally returns interface but I want to know the type when the function is called.

Below is the same code from playground:

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("")
}
  • 写回答

1条回答 默认 最新

  • dousi6192 2016-01-31 06:34
    关注

    To get the struct value, you need to get the interface value's element:

    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
    

    playground example

    This code is helpful for understanding the types in the example:

    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())
    

    The output for &s is:

    ptr *interface {}
    interface interface {}
    struct main.CustomStruct
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作