简体   繁体   中英

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://www.reddit.com/r/golang/comments/g254aa/parse_struct_field_pointers_with_reflection_in/" 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{})
}

Write a function with reflect.Type as an argument. Recurse on pointers and struct fields.

func getFields(t reflect.Type, prefix string) {
    switch t.Kind() {
    case reflect.Ptr:
        getFields(t.Elem(), prefix)
    case reflect.Struct:
        for i := 0; i < t.NumField(); i++ {
            sf := t.Field(i)
            fmt.Println(prefix, sf.Name)
            getFields(sf.Type, prefix+"  ")
        }
    }
}

Use it like this:

getFields(reflect.TypeOf(&Example{}), "")

Run it on the playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM