码迷,mamicode.com
首页 > 其他好文 > 详细

go deep copy map

时间:2019-07-31 23:36:36      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:number   package   body   print   etc   nts   other   cut   keyword   

 

 

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

标签:number   package   body   print   etc   nts   other   cut   keyword   

原文地址:https://www.cnblogs.com/oxspirt/p/11279800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!