-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
reflection.go
79 lines (66 loc) · 1.61 KB
/
reflection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package caches
import (
"errors"
"fmt"
"reflect"
"gorm.io/gorm/schema"
)
func SetPointedValue(dest interface{}, src interface{}) {
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(src).Elem())
}
func deepCopy(src, dst interface{}) error {
srcVal := reflect.ValueOf(src)
dstVal := reflect.ValueOf(dst)
if srcVal.Kind() == reflect.Ptr {
srcVal = srcVal.Elem()
}
if srcVal.Type() != dstVal.Elem().Type() {
return errors.New("src and dst must be of the same type")
}
return copyValue(srcVal, dstVal.Elem())
}
func copyValue(src, dst reflect.Value) error {
switch src.Kind() {
case reflect.Ptr:
src = src.Elem()
dst.Set(reflect.New(src.Type()))
err := copyValue(src, dst.Elem())
if err != nil {
return err
}
case reflect.Struct:
for i := 0; i < src.NumField(); i++ {
if src.Type().Field(i).PkgPath != "" {
return fmt.Errorf("%w: %+v", schema.ErrUnsupportedDataType, src.Type().Field(i).Name)
}
err := copyValue(src.Field(i), dst.Field(i))
if err != nil {
return err
}
}
case reflect.Slice:
newSlice := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
for i := 0; i < src.Len(); i++ {
err := copyValue(src.Index(i), newSlice.Index(i))
if err != nil {
return err
}
}
dst.Set(newSlice)
case reflect.Map:
newMap := reflect.MakeMapWithSize(src.Type(), src.Len())
for _, key := range src.MapKeys() {
value := src.MapIndex(key)
newValue := reflect.New(value.Type()).Elem()
err := copyValue(value, newValue)
if err != nil {
return err
}
newMap.SetMapIndex(key, newValue)
}
dst.Set(newMap)
default:
dst.Set(src)
}
return nil
}