使用嵌入进行Go反射

huangapple go评论82阅读模式
英文:

Go Reflection with Embedding

问题

有没有办法在使用匿名方法嵌入时,从“Parent”结构的方法中访问“Child”结构的名称。

例如:

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”想要“Zebra”

SayName()方法返回“Parent”的type.Name()

我意识到我可以这样做,但由于这是一个API,并且经常被重用,所以我更希望有一个不那么重复的解决方案。

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”

有没有办法实现这个?在Go语言中是否可能?

谢谢。

英文:

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

得分: 2

一个动物类型不知道任何可能包含它们作为成员的类型,所以一个动物方法不能仅根据接收者来给出这个答案。但是这个信息必须来自于斑马方法吗?

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

适用于任何类型,包括斑马。

英文:

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

得分: 2

我使用这种方式来实现后期绑定:

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

这种方式并不完美,但是可以实现后期绑定。

英文:

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.

huangapple
  • 本文由 发表于 2012年4月21日 11:27:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/10255926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定