jeudi 22 novembre 2018

Go - Reflection on slice of pointers

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\n", 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 ?





Aucun commentaire:

Enregistrer un commentaire