编辑++:
如何不在 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"}
我为 type 实现了三个方法Wolf
,我需要实现Tiger
type 的所有方法来实现接口。但是Kingdom
,Phylum
两种类型的方法都是相同的。是否有可能只Family
为Tiger
类型实现方法:
func (t Tiger) Family() string {return "Felidae"}
而不是为每种类型重复所有三种方法?
免责声明
请不要与方法中的简单字符串返回混淆,在实际情况下,我需要不同的方法实现,而不仅仅是预定义的值。使用这种愚蠢的风格,我想避免玷污你的大脑。所以跳过方法根本不是办法。谢谢