go deep copy map

Posted oxspirt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go deep copy map相关的知识,希望对你有一定的参考价值。

 

 

func deepCopyJSON(src map[string]interface, dest map[string]interface) error 
    if src == nil 
        return errors.New("src is nil. You cannot read from a nil map")
    
    if dest == nil 
        return errors.New("dest is nil. You cannot insert to a nil map")
    
    jsonStr, err := json.Marshal(src)
    if err != nil 
        return err
    
    err = json.Unmarshal(jsonStr, &dest)
    if err != nil 
        return err
    
    return nil

  

------------------------

How to copy a map to another map?

To copy a map content need to execute a for loop and fetch the index value 1 by 1 with element and assign it to another map. Below is a short example.
 
package main
 
import (
"fmt"
)
func main()   
    map1 := map[string]int
        "x":1,
        "y":2,
    
    map2 := map[string]int       
     
    /* Copy Content from Map1 to Map2*/
    for index,element := range map1       
         map2[index] = element
    
     
    for index,element := range map2
        fmt.Println(index,"=>",element) 
    
C:\golang\codes>go run example.go
x => 1
y => 2

C:\golang\codes>

以上是关于go deep copy map的主要内容,如果未能解决你的问题,请参考以下文章

Shallow copy and Deep copy

deep-copy

python中的shallow copy 与 deep copy

NumPy学习(索引和切片,合并,分割,copy与deep copy)

deep copy and shallow copy

c_cpp deep_copy.c