feat: 深度克隆支持map复制

This commit is contained in:
2025-11-27 14:50:27 +08:00
parent b0d0a6db28
commit 30c1d54f49
4 changed files with 72 additions and 0 deletions

View File

@ -9,6 +9,7 @@ package op_array
import (
"fmt"
"reflect"
)
// ToMap 数组转map
@ -112,3 +113,34 @@ func Tree[ID comparable, Value any](dataList []Value, formatParentID func(v Valu
}
return rootData
}
// DeepClone 深度克隆一个数组, 每一个元素的地址均重新分配
func DeepClone[Value any](dataList []Value) []Value {
v := *new(Value)
vType := reflect.TypeOf(v)
res := make([]Value, len(dataList))
for i := 0; i < len(dataList); i++ {
newV := new(Value)
switch vType.Kind() {
case reflect.Ptr:
// 解引用, 并单独读取值后重新分配地址
copyV := reflect.New(vType.Elem()).Elem()
copyV.Set(reflect.ValueOf(dataList[i]).Elem())
*newV = copyV.Addr().Interface().(Value)
case reflect.Map:
mapVal := reflect.ValueOf(dataList[i])
mapKeyList := mapVal.MapKeys()
newMap := reflect.MakeMap(vType)
for _, key := range mapKeyList {
// 通过键获取对应的值
value := mapVal.MapIndex(key)
newMap.SetMapIndex(key, value)
}
*newV = newMap.Interface().(Value)
default:
*newV = dataList[i]
}
res[i] = *newV
}
return res
}