-
Notifications
You must be signed in to change notification settings - Fork 0
/
structconv.go
73 lines (61 loc) · 1.54 KB
/
structconv.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
package do
import (
"fmt"
"reflect"
)
// ConvSliceByName fill 'to' struct slice with 'from' by name
func ConvSliceByName[F, T any](from []F, to []T) {
for i, f := range from {
ConvByName(f, to[i])
}
}
// ConvByName fill 'to' struct with 'from' by name
// like to.Name = from.Name
// to must be a struct pointer
func ConvByName[F, T any](from F, to T) {
toByFieldNameReflect(from, to)
}
var (
emptyValue = reflect.Value{}
)
func toByFieldNameReflect[F, T any](from F, to T) {
fromValue := reflect.ValueOf(from)
if fromValue.Type().Kind() == reflect.Pointer {
fromValue = fromValue.Elem()
}
toValue := reflect.ValueOf(to)
if toValue.Type().Kind() != reflect.Pointer {
panic(fmt.Errorf("to is not a pointer"))
}
toElemValue := toValue.Elem()
if toElemValue.Type().Kind() != reflect.Struct {
panic(fmt.Errorf("to is not a struct"))
}
tobytoByFieldNameReflectValue(fromValue, toElemValue)
}
func tobytoByFieldNameReflectValue(fromValue, toElemValue reflect.Value) {
for i := 0; i < toElemValue.Type().NumField(); i++ {
field := toElemValue.Type().Field(i)
fieldValue := toElemValue.Field(i)
// 匿名
if field.Anonymous {
tobytoByFieldNameReflectValue(fromValue, fieldValue)
continue
}
fromFieldValue := fromValue.FieldByName(field.Name)
if fromFieldValue == emptyValue {
continue
}
if fromFieldValue.Type().Kind() != fieldValue.Type().Kind() {
continue
}
fieldValue.Set(fromFieldValue)
}
}
func MakeSlice[T any](l int) (to []*T) {
for i := 0; i < l; i++ {
t := new(T)
to = append(to, t)
}
return
}