mercredi 22 juin 2022

I'm trying to parse a struct field pointers with reflection in Golang

So i want to print the names in a struct(it can be nested), so i'm trying to use a recursive method to do the same but i'm failing to do so.Ive pasted the code below and i get the following error "panic: reflect: call of reflect.Value.NumField on zero Value". I'm able to do it when it's a flat hierarchy but failing when its nested.Any help is appreciated.Also i used this post "https://ift.tt/KEX2OoN" for reference. Also, the struct is built from protobuf hence the Ptr.

package main

import (
    "fmt"
    reflect "reflect"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}
func getFields(protoStructure interface{}) {
    val := reflect.ValueOf(protoStructure).Elem()
    // if val.Kind() == reflect.Ptr {
    // val = val.Elem()
    // }
    valNumFields := val.NumField()
    for i := 0; i < valNumFields; i++ {
        field := val.Field(i)
        fieldKind := field.Kind()
        varDescription := val.Type().Field(i).Tag.Get("description")
        // fieldKindStr := field.Kind().String()
        fieldName := val.Type().Field(i).Name
        // fieldTypeStr := field.Type().String()
        fmt.Println(fieldName, varDescription)
        if fieldKind == reflect.Ptr {
            rvAsserted := field
            getFields(rvAsserted.Interface())
            // fmt.Println(rvAsserted.Type().String())
        }
    }
    return
}
func main() {
    getFields(&DeviceEnv{})
}




Aucun commentaire:

Enregistrer un commentaire