如何在Golang中保留代码DRY

I15*_*159 9 interface dry go 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"}
Run Code Online (Sandbox Code Playgroud)

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

func (t Tiger) Family() string {return "Felidae"}
Run Code Online (Sandbox Code Playgroud)

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

放弃

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

Ain*_*r-G 10

这是经典的作文:

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())
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/Jp22N2IuHL.