douliang9057 2018-07-21 18:42
浏览 90
已采纳

在Golang中深度复制地图

From what I understand, maps are reference types in Go. So assignment will do shallow copy. I plan to do a recursive deep copy of Maps in golang. Recursive because I am dealing with a map that holds the unmarshalled contents of a JSON.

func deepCopyJSON(src map[string]interface{}, dest *map[string]interface{}) error {
    if src == nil || dest == nil {
        return errors.New("src/dest is nil. You cannot insert to a nil map")
    }
    for key, value := range src {
        if reflect.TypeOf(value).String() != jsonType {
            (*dest)[key] = value
        } else {
            (*dest)[key] = make(map[string]int)
//Suspect code below causes the error.
            deepCopyJSON(value.(map[string]interface{}), &(((*dest)[key]).(map[string]interface{})))
        }
    }
    return nil
}

The Error: cannot take the address of (*dest)[key].(map[string]interface {}) How do I get around this? Are there other ways to deep maps?

I primer on the internals of map in golang, will also be useful.

  • 写回答

2条回答 默认 最新

  • douzhi4311 2018-08-04 11:55
    关注
    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败