feat: 深度克隆支持map复制
This commit is contained in:
@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user