gpt4 book ai didi

go - 避免在 "subtypes"之间重复代码

转载 作者:行者123 更新时间:2023-12-02 18:30:17 24 4
gpt4 key购买 nike

我正在将一个旧的 Java 项目重写为 Go。

我已经在工作中完成了一些 Go,但我不知道如何将我的 OOP(带有抽象类等)转换为 Go 哲学。

在这个想法中,我有两种类型(很快就会有 3 种),它们有一些通用的方法,但其他一些类型(最多只有 1 或 2 个)应该具有相同的签名,但不具有相同的主体。

我知道Go没有某种继承。现在我有这样的东西:

type A struct {...}
func (a *A) M1 (){ stuff1 }
func (a *A) M2 (){ stuff2 }
func (a *A) SM (){ special stuff A }

然后:

type B struct {...}
func (b *B) M1 (){ stuff1 }
func (b *B) M2 (){ stuff2 }
func (b *B) SM (){ special stuff B }

我不知道Go是如何管理这个的。在 Java 中,我做了一个抽象类,然后用我的两个具体类实现了它。

我想要的是不必重复 M1() 和 M2(),而是能够有一个泛型类型来调用这些方法,然后只需为这两种类型定义 SM() 即可。

最佳答案

您可以嵌入一个结构,例如:

type Common struct {}

func (c *Common) M1() {
fmt.Println("M1")
}

func (c *Common) M2() {
fmt.Println("M2")
}

type A struct {
Common
}

func (a *A) SM() {
fmt.Println("A SM()")
}

type B struct {
Common
}

func (b *B) SM() {
fmt.Println("B SM()")
}

type Thing interface {
M1()
M2()
SM()
}
func main() {
var a Thing = &A{}
var b Thing = &B{}

a.M1()
b.M2()
a.SM()
b.SM()
}

https://play.golang.org/p/Q3mIH_W8X44

关于go - 避免在 "subtypes"之间重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58757719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com