go - 如何在 Golang 中保持代码 DRY

标签 go interface dry go-interface

编辑++:

如何在 Go 中不重复我的代码?

type Animal interface {
    Kingdom() string
    Phylum() string
    Family() string
}

type Wolf struct {}
type Tiger struct {}

func (w Wolf) Kingdom() string {return "Animalia"}
func (w Wolf) Phylum() string {return "Chordata"}
func (w Wolf) Family() string {return "Canidae"}

我实现了Wolf类型的三个方法,我需要实现Tiger类型的所有方法来实现接口(interface)。但是 KingdomPhylum 方法对于这两种类型是相同的。是否有可能只为 Tiger 类型实现 Family 方法:

func (t Tiger) Family() string {return "Felidae"}

而不是为每种类型重复所有三种方法?

免责声明

请不要与方法中的简单字符串返回混淆,在实际情况下,我需要不同的方法实现,而不仅仅是预定义的值。使用这种愚蠢的风格,我想避免玷污你的大脑。所以跳过方法根本不是办法。谢谢

最佳答案

这是古典作文:

type Wolf struct {
    Animalia
    Chordata
    Canidae
}
type Tiger struct {
    Animalia
    Chordata
    Felidae
}

type Animalia struct{}

func (Animalia) Kingdom() string { return "Animalia" }

type Chordata struct{}

func (Chordata) Phylum() string { return "Chordata" }

type Canidae struct{}

func (Canidae) Family() string { return "Canidae" }

type Felidae struct{}

func (Felidae) Family() string { return "Felidae" }

func main() {
    w := Wolf{}
    t := Tiger{}
    fmt.Println(w.Kingdom(), w.Phylum(), w.Family())
    fmt.Println(t.Kingdom(), t.Phylum(), t.Family())
}

Playground :https://play.golang.org/p/Jp22N2IuHL .

关于go - 如何在 Golang 中保持代码 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242142/

相关文章:

c# - 在 C# 中的每个派生类中都有一个更具体的接口(interface)

javascript - 使用 JavaScript 应用 DRY 原则

java - 什么是基于接口(interface)的框架?

c# - 无法转换异常类型的 COM 对象

javascript - Angular 。如何不重复相同的功能

javascript - 什么是 javascript 事件委托(delegate)以及如何让我的 js 保持干燥?

memory-management - 多部分表单上传+golang中的内存泄漏?

linux - 包裹 。 : C source files not allowed when not using cgo or SWIG: main. c

pointers - 指向空接口(interface)类型断言的指针

json - 向从数据库中获取的电话号码发送短信。代码不工作