json - Golang 中的深度复制 map

标签 json go maps deep-copy

据我了解,映射是 Go 中的引用类型。所以赋值会做浅拷贝。我计划在 golang 中对 map 进行递归深度复制。递归,因为我正在处理一个包含 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
}

错误:无法获取 (*dest)[key].(map[string]interface {}) 的地址 我该如何解决这个问题?有没有其他方法可以加深 map ?

我介绍了 golang 中 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
}

关于json - Golang 中的深度复制 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459083/

相关文章:

java - json ajax问题

asp.net - 使用 jQuery 将 JSON 对象成功发送到 ASP.NET WebMethod

go - 在继承的结构上使用链方法

Golang goroutine无限循环内存泄漏

postgresql - Postgres : Optimising concurrent same row updates

graphics - 从 R 中的一组点在 map 上绘制平滑区域

java - 制作 2D map 最有效的方法?

php - FullCalendar - 通过 ajax 发送 View

javascript - 如何将此字符串转换为 JSON 对象?

java - 查找多个键是否映射到相同的值