我有这段代码:
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\n", d)
fmt.Println(DeepFields(d)) //works fine
// fmt.Println(DeepFields(&d)) //but I need to pass pointer
}
去游乐场:https://play.golang.org/p/1NS29r46Al
我需要使用指针来执行此操作,请参阅第44行。
答案 0 :(得分:0)
为了能够发送指针和值元素,您可以将其添加到DeepFields
函数中:
if ift.Kind() == reflect.Ptr {
ifv = ifv.Elem()
ift = ift.Elem()
}