<p>Could anyone suggest a better implementation of this function that basically merges two slices such as:</p>
<pre><code> 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,
},
}
</code></pre>
<p>The function should return:</p>
<pre><code> []bonus.Bonus{
bonus.Bonus{
Type: "BonusA",
Count: 2,
},
bonus.Bonus{
Type: "BonusB",
Count: 2,
},
bonus.Bonus{
Type: "BonusC",
Count: 2,
},
}
</code></pre>
<p>My off-the-dome implementation is:</p>
<pre><code>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
</code></pre>
<p>}</p>
<p>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.</p>
<hr/>**评论:**<br/><br/>jerf: <pre><p>There's a bit you can remove, such as the fact you can just <a href="https://play.golang.org/p/i-EopSpMY0j" rel="nofollow">+= an empty map entry because you'll start with the 0 value</a>, 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.</p></pre>Ronniemanseaman: <pre><p>So are you saying I can omit the entire else {} block?</p></pre>jerf: <pre><p>The whole if. Leave just the true branch.</p></pre>Ronniemanseaman: <pre><p>Thanks, that is good to know</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传