How to copy a map?

后端 未结 5 742
傲寒
傲寒 2020-12-05 01:36

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 02:06

    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
    }
    

    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
    }
    

    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.

提交回复
热议问题