如何复制地图? [英] How to copy a map?

查看:123
本文介绍了如何复制地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将另一个( aSuperMap )中的地图内容( amap )和然后清除 amap ,以便它可以在下一次迭代/循环中获取新值。
问题在于,您无法在supermap中清除地图而不清除其参考
这里是一些伪代码。

I'm trying to copy the contents of a map ( amap ) inside another one (aSuperMap) and then clear amap so that it can take new values on the next iteration/loop. The issue is that you can't clear the map without to clear its reference in the supermap as well. Here is some pseudo code.

for something := range fruits{
        aMap := make(map[string]aStruct)
        aSuperMap := make(map[string]map[string]aStruct)

        for x := range something{
            aMap[x] = aData
            aSuperMap[y] = aMap
            delete(aMap, x)
    }
//save aSuperMap
  saveASuperMap(something)

}

我也尝试了一些动态的东西,但显然它会抛出一个错误(不能赋给nil) / p>

I've also tried some dynamic stuff but obviously it throws an error (cannot assign to nil)

aSuperMap[y][x] = aData

问题是我该如何创建一个关联映射?在PHP中,我只需使用aSuperMap [y] [x] = aData。看来,golang没有任何明显的方法。如果我删除 delete(aMap,x),则超级地图的引用也会被删除。如果我不删除它,supermap会以重复数据结束。基本上在每个循环中,它都会得到 aMap ,新值加上所有旧值。

The question is how can I create an associative map ? In PHP I simply use aSuperMap[y][x] = aData. It seems that golang doesn't have any obvious method. If I delete delete(aMap, x) its reference from the super map is deleted as well. If I don't delete it the supermap ends up with duplicate data. Basically on each loop it gets aMap with the new value plus all the old values.

推荐答案

您不复制地图,而是复制地图。因此, delete 会修改原始地图和超级地图中的值。要复制地图,您必须使用作为循环,如下所示:

You are not copying the map, but the reference to the map. Your delete thus modifies the values in both your original map and the super map. To copy a map, you have to use a for loop like this:

for k,v := range originalMap {
  newMap[k] = v
}

下面是一个来自现在退役的SO文档的例子:

Here's an example from the now-retired SO documentation:

// Create the original map
originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2

// Create the target map
targetMap := make(map[string]int)

// Copy from the original map to the target map
for key, value := range originalMap {
  targetMap[key] = value
}




a href =https://web.archive.org/web/20171006194258/https://stackoverflow.com/documentation/go/732/maps/9834/copy-a-map#t=20171006194258443316 =noreferrer >地图 - 复制地图。原作者是 JepZ 。可以在撰稿人页面上找到归因详情。该源根据 CC BY-SA 3.0 进行许可,可以在文档档案。参考主题ID:732和示例ID:9834。

Excerpted from Maps - Copy a Map. The original author was JepZ. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 732 and example ID: 9834.

这篇关于如何复制地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆