本文介绍了在Golang中深度复制地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
据我了解,地图是Go中的参考类型.因此,作业将进行浅表复制.我计划在golang中进行Maps的递归深层复制.递归的,因为我正在处理一个包含JSON的未编组内容的映射.
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
}
错误:不能使用(* dest)[key]的地址.(map [string] interface {})我该如何解决?还有其他深层地图的方法吗?
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?
我在golang的map的内部结构上入门,也很有用.
I primer on the internals of map in golang, will also be useful.
推荐答案
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
}
这篇关于在Golang中深度复制地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!