zoukankan      html  css  js  c++  java
  • 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:golangcodes>go run example.go
    x => 1
    y => 2

    C:golangcodes>
  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/oxspirt/p/11279800.html
Copyright © 2011-2022 走看看