Go Reflection with Embedding

浪尽此生 提交于 2019-12-11 08:16:44

问题


Is there a way to access the name of a "Child" struct from methods on the "Parent" struct when using anonymous method embedding.

For Example:

type Animal struct{}

func (a Animal) SayName() string {
    v := reflect.TypeOf(a)
    return v.Name()
}

type Zebra struct {
    Animal
}

var zebra Zebra
zebraName := zebra.SayName() // "Animal" want "Zebra"

The SayName() method returns the type.Name() of the "Parent".

I realize I could do something like this, but since this for an API and will be reused often. I would prefer to have a solution that is less repetitive.

type Animal struct{
  Name string
}

func (a Animal) SayName() string {
    return a.Name
}

type Zebra struct {
    Animal
}

zebra := &Zebra{Name:"Zebra"}
zebraName := zebra.SayName() // "Zebra"

Any ideas on how this could be accomplished? Is this possible in Go?

Thank you.


回答1:


An Animal type doesn't know anything about types which may include them as members, so an Animal method can't give you this answer based on the receiver alone. But must this information come from a Zebra method?

func SayName(a interface{}) string {
    return reflect.TypeOf(a).Name()
}

works for any type, Zebras included.




回答2:


I use this way to achieve the late binding:

http://play.golang.org/p/03-rs4bLaV

Which is not so perfect, but a way to achieve this.



来源:https://stackoverflow.com/questions/10255926/go-reflection-with-embedding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!