在Go中合并地图(Merging maps in Go)
在Go中,将键值对从一张地图合并到另一张地图的最佳方式是什么? 我正在使用一个简单的循环,但我想知道是否有像PHP的array_merge可以使用。
bigmap := map[string]string{"a":"a", "b":"b", "c":"c"} smallmap := map[string]string{"d":"d"} for k, v := range smallmap { bigmap[k] = v }What's the best way to merge key-value pairs from one map into another in Go? I'm using a simple loop, but I was wondering if there's something like PHP's array_merge that could be used.
bigmap := map[string]string{"a":"a", "b":"b", "c":"c"} smallmap := map[string]string{"d":"d"} for k, v := range smallmap { bigmap[k] = v }最满意答案
不,没有。
这不会如你所写的明确代码足够短,并且具有不隐藏实现的优点。
如果你需要它,你可以做你自己的功能:
func addmap(a map[string]string, b map[string]string) { for k,v := range b { a[k] = v } } addmap(bigmap, smallmap)但是因为Go没有泛型,所以你必须为你想要使用的每个具体的地图类型制作一个不同的函数。
No, there isn't.
This wouldn't be so useful as the clear code you wrote is short enough and has the advantage of not hiding the implementation.
You can do your own function if you need it :
func addmap(a map[string]string, b map[string]string) { for k,v := range b { a[k] = v } } addmap(bigmap, smallmap)But as Go has no generics, you would have to make a different function for each concrete map type you want to use.
更多推荐
发布评论