donglan7594 2018-03-02 06:26
浏览 40
已采纳

如何处理将另一种类型封装为参数的结构片

I have two structs (Dimension and Metric) and part of their attributes overlap, so I decided to go with a common struct that is then encapsulated.

type Attribute struct {
    Function *string
    Id *string
}

type Dimension struct {
    Attribute
    Class *string
}

type Metric struct {
    Alias *string
    Attribute
}

What I would like is to have a function that takes a slice of either Dimensions or a slice of Metrics and sorts it by the id field, which is common between the two.

dimensions := []Dimension{...}
metrics := []Metric{...}
sortById(dimensions)
sortById(metrics)

I could use a slice of interface types func sortItems(items []interface{}) but I would prefer to avoid this so I was wondering how I can do something like the lines below.

func sortItems(items []Attribute) {
    //Sort here
}

If I try this, I am getting cannot use metrics (type []Metric) as type []Attribute in argument to this.sortItems which is to be expected, but I am new enough to Go not to know how to approach this.

I know I could just create two functions (one for each type) but I am curious what the correct pattern is for tackling issues like these in Go.

  • 写回答

1条回答 默认 最新

  • dongzhuo3202 2018-03-02 06:32
    关注

    Define an interface and have it be implemented by the common type Attribute.

    Something like this:

    type Attributer interface {
        GetId() *int
    }
    
    func (a Attribute) GetId() *int {
        return a.Id
    }
    
    func sortItems(items []Attributer) {
        //Sort here
    }
    

    By virtue of embedding the Attribute type, both Dimension and Metric can be used wherever the Attributer interface is expected.

    So this will compile just fine.

    items := []Attributer{Dimension{}, Metric{}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值