如何在 Golang 中调用 parent 方法并将扩展 parent 结构的任何 child 作为参数传递
How to call parent method and pass any child that extending the parent struct as argument in Golang
我还在学习Golang,想请教一下。
是否可以做这样的事情并将任何其他 child 传递给扩展 Parent 结构的 PMethod?
type Parent struct{
PAttribute string
}
func (p *Parent) PMethod(c *Child){
fmt.Println("this is parent Attribute : " + p.PAttribute)
fmt.Println("this is child Attribute : " + c.CAttribute)
}
type Child struct{
Parent
CAttribute string
}
type Child2 struct{
Parent
CAttribute string
}
func main(){
c := Child{
Parent{
"parent"
},
"child",
}
c.PMethod(&c)
c2 := Child2{
Parent{
"parent"
},
"child",
}
c2.PMethod(&c2)
}
谢谢
正如其他人所说,忘记继承,Go 中的 Go doesn't have inheritance for good reasons. So stop thinking in terms of parents and children. Go has composition (which you're using here), but it behaves differently. You could use interfaces 是为了传递 Child 和 Child2 并且让接收者对它得到的是哪一个无动于衷(只要它具有相同的功能)。但这可能是一个错误,因为您正在尝试重新创建您在 Go 中熟悉的继承。不要那样做。
如果您的类型像这样相关,您可能应该从嵌入式 class 接受 class 实例进行修改。嵌入的 class 应该作用于它自己的字段,仅此而已 - 这将关注点区分开来并使用作用于它的方法保存数据。因此,与其考虑 Parents 和 Children,不如考虑一下您想分享的 code/data。
考虑 classic 继承问题动物 - 有猫和狗。通过继承,您将拥有一只猫和一只狗以及一个抽象基础 class 动物。 Animal 可能具有您期望的所有方法,然后您可能在 Animal 上编写一个什么都不说的 Say() 方法和一个发出呜呜声的 Say() 和一个对狗和猫喵喵叫的 Say() 方法。
在 Go 中,您只需使用 Cats and Dogs 和不同的 Say() 方法,它们都符合其他人定义的 Speaker() 接口。宁愿有一点重复,也不愿大量额外的代码和复杂性,只是为了分享一点行为。
一定要阅读 Effective Go 并尝试使用可用的工具,而不是重新创建您熟悉的继承等工具。
我还在学习Golang,想请教一下。 是否可以做这样的事情并将任何其他 child 传递给扩展 Parent 结构的 PMethod?
type Parent struct{
PAttribute string
}
func (p *Parent) PMethod(c *Child){
fmt.Println("this is parent Attribute : " + p.PAttribute)
fmt.Println("this is child Attribute : " + c.CAttribute)
}
type Child struct{
Parent
CAttribute string
}
type Child2 struct{
Parent
CAttribute string
}
func main(){
c := Child{
Parent{
"parent"
},
"child",
}
c.PMethod(&c)
c2 := Child2{
Parent{
"parent"
},
"child",
}
c2.PMethod(&c2)
}
谢谢
正如其他人所说,忘记继承,Go 中的 Go doesn't have inheritance for good reasons. So stop thinking in terms of parents and children. Go has composition (which you're using here), but it behaves differently. You could use interfaces 是为了传递 Child 和 Child2 并且让接收者对它得到的是哪一个无动于衷(只要它具有相同的功能)。但这可能是一个错误,因为您正在尝试重新创建您在 Go 中熟悉的继承。不要那样做。
如果您的类型像这样相关,您可能应该从嵌入式 class 接受 class 实例进行修改。嵌入的 class 应该作用于它自己的字段,仅此而已 - 这将关注点区分开来并使用作用于它的方法保存数据。因此,与其考虑 Parents 和 Children,不如考虑一下您想分享的 code/data。
考虑 classic 继承问题动物 - 有猫和狗。通过继承,您将拥有一只猫和一只狗以及一个抽象基础 class 动物。 Animal 可能具有您期望的所有方法,然后您可能在 Animal 上编写一个什么都不说的 Say() 方法和一个发出呜呜声的 Say() 和一个对狗和猫喵喵叫的 Say() 方法。
在 Go 中,您只需使用 Cats and Dogs 和不同的 Say() 方法,它们都符合其他人定义的 Speaker() 接口。宁愿有一点重复,也不愿大量额外的代码和复杂性,只是为了分享一点行为。
一定要阅读 Effective Go 并尝试使用可用的工具,而不是重新创建您熟悉的继承等工具。