普通网友 2012-08-29 06:43
浏览 88
已采纳

在Go中合并地图

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
}
  • 写回答

2条回答 默认 最新

  • duancheng3042 2012-08-29 07:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码