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
", 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?
EDIT: got what I needed:
func printFields(prefix string, t reflect.Type) {
if t.Kind() != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("%v%v %v
", 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 {
printFields(fmt.Sprintf(" %v", prefix), f.Type.Elem())
}
}
}
func printExpandedStruct(s interface{}) {
printFields("", reflect.ValueOf(s).Type())
}