加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何在Golang中保留代码DRY

发布时间:2020-12-16 19:29:27 所属栏目:大数据 来源:网络整理
导读:编辑: 如何不在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 "Chor
编辑:

如何不在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类型的所有方法来实现接口.但是这两种类型的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())
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读