I have a 'common' structure promoted within two specific structures. For example:
type common struct {
name string
}
type apple struct {
common
}
type orange struct {
common
}
Details specific to apple
and orange
are omitted.
I have a type-specific map of each, e.g., map[string]*apple
and map[string]*orange
.
I am trying to make a single function that can extract the common
pointers. From what I've tried so far, reflection appears required.
My function is:
func getFruitArray(theMap interface{}) []*common {
m := reflect.ValueOf(theMap)
cf := make([]*common, 0, m.Len())
for _, mk := range m.MapKeys() {
v := m.MapIndex(mk)
cf = append(cf, v.Interface().(*common))
}
return cf
}
This function fails at cf = append(cf, v.Interface().(*common))
with:
panic: interface conversion: interface {} is *main.apple, not *main.common
Is there a way to access the promoted struct common
without specifically referencing apple
or orange
in this function?
Aucun commentaire:
Enregistrer un commentaire