I have a struct
named Parent
that is designed to be used in composition:
package main
import (
"fmt"
"reflect"
)
type Parent struct {
Field1 int
}
func (p *Parent) Display() {
t := reflect.TypeOf(p).Elem()
for i := 0; i < t.NumField(); i++ {
fmt.Println(t.Field(i).Name)
}
}
type Child struct {
Parent
Field2 int
}
func main() {
c := &Child{}
c.Display()
}
I would like the parent to be able to access both Field1
and Field2
using reflection. For example, the code above will only output Field1
since the type of p
is Parent
.
Is there a way (using reflection) for Display()
to determine that the Parent
is part of a Child
and display all of its fields as well? Unfortunately, I cannot perform a .(*Child)
type assertion since many different types will be using Parent
.
Aucun commentaire:
Enregistrer un commentaire