-
Notifications
You must be signed in to change notification settings - Fork 60
/
new_model.go
60 lines (56 loc) · 1.57 KB
/
new_model.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
package uadmin
import (
"reflect"
)
// NewModel creates a new model from a model name
func NewModel(modelName string, pointer bool) (reflect.Value, bool) {
model := models[modelName]
if model == nil {
return reflect.ValueOf(nil), false
}
m := reflect.New(reflect.TypeOf(model)).Elem()
if pointer {
m = m.Addr()
}
return m, true
}
// NewModelArray creates a new model from a model name
func NewModelArray(modelName string, pointer bool) (reflect.Value, bool) {
model := models[modelName]
if model == nil {
return reflect.ValueOf(nil), false
}
modelType := reflect.TypeOf(model)
m := reflect.New(reflect.SliceOf(modelType)).Elem()
m.Set(reflect.MakeSlice(reflect.SliceOf(modelType), 0, 0))
if pointer {
m = m.Addr()
}
return m, true
}
// deepCopy for ModelSchema
func deepCopy(a interface{}) interface{} {
b := a
valueOfA := reflect.ValueOf(a)
valueOfB := reflect.New(reflect.TypeOf(a)).Elem()
valueOfB.Set(reflect.ValueOf(b))
t := reflect.TypeOf(a)
for i := 0; i < t.NumField(); i++ {
if t.Field(i).Type.Kind() == reflect.Slice {
dst := reflect.New(reflect.SliceOf(t.Field(i).Type.Elem())).Elem()
for index := 0; index < valueOfA.Field(i).Len(); index++ {
temp := valueOfA.Field(i).Index(index)
if temp.Kind() == reflect.Struct {
x := temp.Interface()
valueOfX := reflect.New(reflect.TypeOf(temp.Interface())).Elem()
valueOfX.Set(reflect.ValueOf(deepCopy(x)))
dst = reflect.Append(dst, valueOfX)
} else {
dst = reflect.Append(dst, temp)
}
}
valueOfB.Addr().Elem().Field(i).Set(dst)
}
}
return valueOfB.Interface()
}