首页 > 文章列表 > Golang 中的深度复制map?

Golang 中的深度复制map?

golang
351 2023-04-13

问题内容

Golang 中的深度复制map?

正确答案

在 Golang 中,想要深度复制一个 map 可以通过以下方法:

func DeepCopyMap(m map[string]interface{}) map[string]interface{} {
    copyMap := make(map[string]interface{})
    for k, v := range m {
        switch v.(type) {
        case map[string]interface{}:
            copyMap[k] = DeepCopyMap(v.(map[string]interface{}))
        case []interface{}:
            copyMap[k] = DeepCopySlice(v.([]interface{}))
        default:
            copyMap[k] = v
        }
    }
    return copyMap
}

func DeepCopySlice(s []interface{}) []interface{} {
    copySlice := make([]interface{}, len(s))
    for i, v := range s {
        switch v.(type) {
        case map[string]interface{}:
            copySlice[i] = DeepCopyMap(v.(map[string]interface{}))
        case []interface{}:
            copySlice[i] = DeepCopySlice(v.([]interface{}))
        default:
            copySlice[i] = v
        }
    }
    return copySlice
}

这个方法会检查 map 中的每个值,如果是 map 或 slice 类型,就递归地调用 DeepCopyMap 或 DeepCopySlice 进行深度复制。如果是其他类型,则直接赋值给 copyMap。