本文介绍了用嵌入去思考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:

有没有办法从Parent / p>

 类型动态结构{} 

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

类型Zebra结构{
动物
}

var zebra斑马
zebraName:=斑马条款()/ /动物想要斑马条款

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



我意识到我可以做这样的事情,但因为这是一个API,并且会经常重复使用。

 类型动态结构{
名称字符串
我希望有一个不太重复的解决方案。 }

func(a Animal)SayName()字符串{
返回a.Name
}

类型斑马结构{
Animal

$ b $斑马纹=&斑马{名称:斑马纹}
斑马纹名:=斑马条纹。 $ c>

关于如何实现这一点的任何想法?



谢谢。

解决方案

动物类型不知道任何可能包括它们作为成员的类型,所以动物方法不能仅基于接收者给你这个答案。但是,这些信息是否必须来自Zebra方法?

  func SayName(接口{})string {
return .TypeOf(a).Name()
}

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


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.

解决方案

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.

这篇关于用嵌入去思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 06:08