lundi 8 octobre 2018

Recursively expanding struct definition containing pointers

This question based on following: go reflection deeply in struct I need same thing - expand struct definition to pass it then as JSON object but with only difference that struct contains pointers to another structs. So, provided code unable to handle that. I tried to modify it in following way:

func printFields(prefix string, t reflect.Type) {
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Printf("%v%v %v\n", prefix, f.Name, f.Type)
        if f.Type.Kind() == reflect.Struct {
            fmt.Println(reflect.New(f.Type))
            printFields(fmt.Sprintf("  %v", prefix), f.Type)
        } else if f.Type.Kind() == reflect.Ptr {
            fmt.Println("type ", f.Type )
            printFields(fmt.Sprintf("  %v", prefix), f.Type)
        }
    }
}

But it falls to panic in a case of pointers. How to fix that?





Aucun commentaire:

Enregistrer un commentaire