drls2738 2016-10-25 14:03
浏览 42
已采纳

如何在Golang中保持代码DRY

EDIT++:

How to not to repeat my code in 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"}

I implemented a three methods for Wolf type and I need to implement all the methods for Tiger type to implement the interface. But Kingdom and Phylum methods are the same for both types. Is it somehow possible to implement only Family method for Tiger type:

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

and not to repeat all the three methods for each type?

Disclaimer

Please don't be confused with simple string returns in the methods, in a real case I need different method implementations not just pre-defined values. Using this silly style I want to avoid of defiling your brains. So skip methods at all is not the way. Thanks

  • 写回答

3条回答 默认 最新

  • duanhong1985 2016-10-25 14:10
    关注

    This is classical composition:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。