I have a struct like this :
type Parent struct {
example string
}
func (p *Parent) GetMyAttr() {
typ := reflect.TypeOf(p).Elem()
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
fmt.Println(p.Name, ":", p.Type)
}
}
}
And if I have another struct like this :
type Child struct {
Parent
another string
}
call GetTypeOfMe() in child like this
ch := Child{Parent{"example"},"another"}
ch.GetMyAttr()
is always return example : string
. Is this possible to get Child struct in Parent struct with reflection?
Full code is here http://play.golang.org/p/ej4Xh_V2J1
Thanks.
It doesn't work like this, reflect.TypeOf(p).Elem()
will always return Parent
you have 2 options, either implement GetMyAttr
for each child or use a generic function like :
func GetAttr(i interface{}) {
typ := reflect.Indirect(reflect.ValueOf(i)).Type()
fmt.Println(typ)
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
fmt.Println(p.Name, ":", p.Type)
}
}
No, since you operate on a *Parent
, not a *Child
.
This would "work" (play.golang)
func (p *Child) GetMyAttr() {...
would output:
Parent : main.Parent
another : string
A Parent
doesn't know about the struct
which might embed it, so the reflection operates only on Parent
struct.
You see a similar issue with "Go Reflection with Embedding", which uses interface{}
to get to all the struct passed in parameter.