I have this code:
package main
import (
"fmt"
"reflect"
)
type B struct {
X string
Y string
}
type D struct {
B
Z string
}
func DeepFields(iface interface{}) []reflect.Value {
fields := make([]reflect.Value, 0)
ifv := reflect.ValueOf(iface)
ift := reflect.TypeOf(iface)
for i := 0; i < ift.NumField(); i++ {
v := ifv.Field(i)
switch v.Kind() {
case reflect.Struct:
fields = append(fields, DeepFields(v.Interface())...)
default:
fields = append(fields, v)
}
}
return fields
}
func main() {
b := B{"this is X", "this is Y"}
d := D{b, "this is Z"}
// fmt.Printf("%#v
", d)
fmt.Println(DeepFields(d)) //works fine
// fmt.Println(DeepFields(&d)) //but I need to pass pointer
}
Go Playground: https://play.golang.org/p/1NS29r46Al
I need to do it using a pointer, see the line #44.
To be able to send both pointer and value elements, you can add this to your DeepFields
function:
if ift.Kind() == reflect.Ptr {
ifv = ifv.Elem()
ift = ift.Elem()
}
Modified playground: https://play.golang.org/p/MgB-W81dYr