-3
にrelfectを使用して埋め込まれた構造体を横断するために、私はこのコードを持っている:どのようにポインタから構造体
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を参照してください。
ポストコード:
は遊び場を修正。 –
あなたが探している方法は、 'Elem()'と呼ばれています。 – Volker
@roshan_nazareth私はここで完全なコードを配置することはできません、あなたplay.golang.orgでそれを見てください、あなたはそこにそれを実行することができますか? –