Removing duplicates and counting occurrences of structs in slice

blov · 2018-04-07 01:30:10 · 650 次点击    
这是一个分享于 2018-04-07 01:30:10 的资源,其中的信息可能已经有所发展或是发生改变。

Could anyone suggest a better implementation of this function that basically merges two slices such as:

    existingBonuses := []bonus.Bonus{
    bonus.Bonus{
        Type:  "BonusA",
        Count: 1,
    },
    bonus.Bonus{
        Type:  "BonusC",
        Count: 2,
    },
}

    newBonuses := []bonus.Bonus{
    bonus.Bonus{
        Type:  "BonusA",
        Count: 1,
    },
    bonus.Bonus{
        Type:  "BonusB",
        Count: 2,
    },
}

The function should return:

     []bonus.Bonus{
    bonus.Bonus{
        Type:  "BonusA",
        Count: 2,
    },
    bonus.Bonus{
        Type:  "BonusB",
        Count: 2,
    },
    bonus.Bonus{
        Type:  "BonusC",
        Count: 2,
    },
}

My off-the-dome implementation is:

func (u *User) mergeBonuses(bonuses []bonus.Bonus) {
result := make(map[string]int)
merged := append(u.Bonuses, bonuses...)
for _, b := range merged {
    if _, ok := result[b.Type]; ok {
        result[b.Type] += b.Count
    } else {
        result[b.Type] = b.Count
    }
}
r := make([]bonus.Bonus, 0)
for k, v := range result {
    b := bonus.Bonus{
        Type:  k,
        Count: v,
    }
    r = append(r, b)
}
u.Bonuses = r

}

But I was wondering if someone could point out a better or more Golang-like way to do it. Specifically I feel there should be a way to do it avoiding the second loop.


评论:

jerf:

There's a bit you can remove, such as the fact you can just += an empty map entry because you'll start with the 0 value, but at its core, that's what you're looking at, yes. Go doesn't have the sort of basic functional programming tools that are in most modern languages.

Ronniemanseaman:

So are you saying I can omit the entire else {} block?

jerf:

The whole if. Leave just the true branch.

Ronniemanseaman:

Thanks, that is good to know


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

650 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传