Go Reflection with Embedding

2019-08-01 13:02发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-01 13:26

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.

查看更多
贼婆χ
3楼-- · 2019-08-01 13:30

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.

查看更多
登录 后发表回答