Inheritance golang做继承的方式,变通方法
我知道golang不支持继承,但在go中,正确的方法是什么Inheritance golang做继承的方式,变通方法,inheritance,go,Inheritance,Go,我知道golang不支持继承,但在go中,正确的方法是什么 type CommonStruct struct{ ID string } type StructA struct{ CommonStruct FieldA string } type StructB struct{ CommonStruct FieldB string } func (s *CommonStruct) enrich(){ s.ID = IDGenerator() } 如果下面的函数 fu
type CommonStruct struct{
ID string
}
type StructA struct{
CommonStruct
FieldA string
}
type StructB struct{
CommonStruct
FieldB string
}
func (s *CommonStruct) enrich(){
s.ID = IDGenerator()
}
如果下面的函数
func doSomthing(s *CommoStruct){
s.enrich()
}
您可以使用以下界面:
type MyInterface interface {
enrich()
}
func doSomthing(s MyInterface){
s.enrich()
}
任何定义了接口的每个函数或方法的结构都被视为所述接口的实例。您现在可以将带有CommonStruct
的任何内容传递到doSomething()
,因为CommonStruct
定义了increment()
。如果要为特定结构重写increment()
,只需为该结构定义increment()
。例如:
type CommonStruct struct{
ID string
}
type StructA struct{
*CommonStruct
}
type StructB struct{
*CommonStruct
}
type MyInterface interface {
enrich()
}
func doSomething(obj MyInterface) {
obj.enrich()
}
func (this *CommonStruct) enrich() {
fmt.Println("Common")
}
func (this *StructB) enrich() {
fmt.Println("Not Common")
}
func main() {
myA := &StructA{}
myB := &StructB{}
doSomething(myA)
doSomething(myB)
}
印刷品:
普通的不常见
.thansk Steve,它确实已经开始工作了,但是我没有正确地表达我的想法,我已经编辑了这篇文章,你能再看一看吗?再次感谢史蒂夫,但这是否意味着我必须为每个“子结构”单独进行impl-on-enrich?但是如果enrich总是做同样的事情(分配ID等),并且如果我可以将其用于所有“子结构”,那该怎么办呢