在Go中合并地图(Merging maps in Go)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
在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.

更多推荐

本文发布于:2023-04-12 20:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/0fb0cc1bce81ec674118d2ab9b09e31e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:地图   Merging   maps

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!