inheritance - golang 的继承方式,解决方法

标签 inheritance go

我知道 golang 不支持继承,但是在 go for the following 中正确的做法是什么?

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()
}

最佳答案

你可以使用一个接口(interface):

type MyInterface interface {
    enrich()
}

func doSomthing(s MyInterface){
  s.enrich()
}

任何定义了接口(interface)的每个函数或方法的结构都被认为是所述接口(interface)的实例。您现在可以将带有 CommonStruct 的任何内容传递给 doSomething(),因为 CommonStruct 定义了 enrich()。如果您想为特定结构覆盖 enrich(),只需为该结构定义 enrich()。例如:

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)
}

打印:

Common
Not Common

Test it here! .

关于inheritance - golang 的继承方式,解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051299/

相关文章:

go - goroutines的执行顺序

python - Golang单元测试python函数

java - 子类构造函数中的重写函数 (JAVA)

html - 如何防止子选择器失败的 CSS 继承?

go - 构建命令行参数 : cannot load go-sql-driver/mysql

string - 在 Go 中替换 URL 中的协议(protocol)和主机名

c++ - 虚拟析构函数是继承的吗?

c++ - 如何在两个子类之间正确实现赋值运算符

java - 关于在Java中使用继承时的构造函数初始化顺序

go - 为 template.ParseFiles 指定模板文件名