在Go中合并地图

huangapple go评论88阅读模式
英文:

Merging maps in Go

问题

什么是在Go语言中将一个map的键值对合并到另一个map的最佳方法?我正在使用一个简单的循环,但我想知道是否有类似于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
}

答案1

得分: 9

不,没有。

这样做并不那么有用,因为你写的清晰代码已经足够简短,并且具有不隐藏实现的优势。

如果需要的话,你可以自己编写一个函数:

func addmap(a map[string]string, b map[string]string) {
    for k,v := range b {
        a[k] = v
    }
}

addmap(bigmap, smallmap)

但是由于Go语言没有泛型,你需要为每种具体的map类型编写不同的函数。

英文:

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.

答案2

得分: 1

据我所知,没有内置的或者库函数可以做到这一点。而且我认为你的代码已经是最好的了。

英文:

AFAIK, there's no built-in nor library function for that. And I think your code is as good as it can get.

huangapple
  • 本文由 发表于 2012年8月29日 14:43:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/12172215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定