编辑++:
如何在 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)。但是 Kingdom
和 Phylum
方法对于这两种类型是相同的。是否有可能只为 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/