【问题标题】:Golang - best practice for using same function for two structs with same fieldGolang - 对具有相同字段的两个结构使用相同函数的最佳实践
【发布时间】:2022-10-30 15:38:26
【问题描述】:

想象一下我有这两个结构:

type Game struct {
    Name string
    MultiplayerSupport bool
    Genre string
    Version string
}

type ERP struct {
    Name string
    MRPSupport bool
    SupportedDatabases []string
    Version string
}

我想要一个附加到这些结构的函数,它将打印Version 变量

func (e *ERP) PrintVersion()  {
    fmt.Println("Version is", e.Version)
}

我知道我可以使用接口,但我仍然必须为这两个结构定义两个相同的函数,即代码重复。

防止代码重复的最佳做法是什么?

附言在使用“此问题已在此处有答案”标记之前,这不是同一个问题,因为在以下问题中,结构之间的字段名称不同。

Best practice to use the same function with different structs - Golang

【问题讨论】:

    标签: go methods struct


    【解决方案1】:

    当我准备这个问题时,我突然想到我可以实现这样的东西:

    type Version string
    
    func (v Version) PrintVersion() {
        fmt.Println("Version is", v)
    }
    

    因为所有自定义类型(不仅是结构)都可以是方法接收器。

    然后我可以使用composition 在结构上使用这种类型:

    type Game struct {
        Name               string
        MultiplayerSupport bool
        Genre              string
        Version
    }
    
    type ERP struct {
        Name               string
        MRPSupport         bool
        SupportedDatabases []string
        Version
    }
    

    然后我可以像使用普通字符串字段一样使用它(确实如此!)

    func main() {
    
        g := Game{
            "Fear Effect",
            false,
            "Action-Adventure",
            "1.0.0",
        }
    
        g.PrintVersion()
        // Version is 1.0.0
    
    
        e := ERP{
            "Logo",
            true,
            []string{"ms-sql"},
            "2.0.0",
        }
    
        e.PrintVersion()
        // Version is 2.0.0
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 2017-04-25
      • 2023-01-18
      • 2016-02-20
      • 1970-01-01
      • 2015-03-26
      相关资源
      最近更新 更多