53 lines
1.1 KiB
Markdown
53 lines
1.1 KiB
Markdown
|
### 深拷贝map
|
||
|
|
||
|
### 方法一 encoding/gob包
|
||
|
|
||
|
```go
|
||
|
import "encoding/gob"
|
||
|
// 需要什么类型的map注册类型就可以
|
||
|
func DeepCopy(dst, src interface{}) error {
|
||
|
var buf bytes.Buffer
|
||
|
gob.Register(map[string]interface{}{})
|
||
|
gob.Register([]interface{}(nil))
|
||
|
gob.Register([]map[string]interface{}{})
|
||
|
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
|
||
|
}
|
||
|
```
|
||
|
|
||
|
### 方法二 json 序列化后反序列化
|
||
|
|
||
|
```go
|
||
|
func MapDeepCopy(src, dst interface{}) error {
|
||
|
byteSlice, err := json.Marshal(src)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return json.Unmarshal(byteSlice, dst)
|
||
|
}
|
||
|
```
|
||
|
|
||
|
### 方法三 循环遍历
|
||
|
|
||
|
```go
|
||
|
func DeepCopy(value interface{}) interface{} {
|
||
|
if valueMap, ok := value.(map[string]interface{}); ok {
|
||
|
newMap := make(map[string]interface{})
|
||
|
for k, v := range valueMap {
|
||
|
newMap[k] = DeepCopy(v)
|
||
|
}
|
||
|
return newMap
|
||
|
} else if valueSlice, ok := value.([]interface{}); ok {
|
||
|
newSlice := make([]interface{}, len(valueSlice))
|
||
|
for k, v := range valueSlice {
|
||
|
newSlice[k] = DeepCopy(v)
|
||
|
}
|
||
|
return newSlice
|
||
|
}
|
||
|
return value
|
||
|
}
|
||
|
```
|
||
|
|