据我了解,映射是 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/