douhuiyan2772 2018-11-23 01:36
浏览 64
已采纳

对指针的思考

I am trying to reflect a slice of pointers on a struct stored in an interface{}

I think I am doing ok until it's time to introspect the content on the pointed struct. See the below example

package main

import (
    "fmt"
    "reflect"
)

type teststruct struct {
    prop1 string
    prop2 string
}

func main() {   
    test := teststruct{"test", "12"}

    var container interface{}

    var testcontainer []*teststruct

    testcontainer = append(testcontainer, &test)

    container = testcontainer   

    rcontainer := reflect.ValueOf(container)
    fmt.Println(rcontainer.Kind())

    rtest := rcontainer.Index(0).Elem()
    fmt.Println(rtest)

    rteststruct := reflect.ValueOf(rtest)
    fmt.Println(rteststruct.Kind())

    typeOfT := rteststruct.Type()

    for i := 0; i < rteststruct.NumField(); i++ {
        f := rteststruct.Field(i)
        fmt.Printf("%d: %s %s = %v
", i, typeOfT.Field(i).Name, f.Type(), f.String())
    } 
}

Which results

slice
{test 12}
struct
0: typ *reflect.rtype = <*reflect.rtype Value>
1: ptr unsafe.Pointer = <unsafe.Pointer Value>
2: flag reflect.flag = <reflect.flag Value>

I am definitely missing something here, someone would be able to explain me what ?

  • 写回答

1条回答 默认 最新

  • doushi3454 2018-11-23 02:49
    关注

    rtest := rcontainer.Index(0).Elem() is already the value, so when you do this: rteststruct := reflect.ValueOf(rtest), you are actually getting a reflect.Value which is of course a struct.

    Replace the end of your code with this:

    typeOfT := rtest.Type()
    
    for i := 0; i < rtest.NumField(); i++ {
        f := rtest.Field(i)
        fmt.Printf("%d: %s %s = %v
    ", i, typeOfT.Field(i).Name, f.Type(), f.String())
    }
    

    Playground

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

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题