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

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP