-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct.go
63 lines (53 loc) · 1.05 KB
/
struct.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
package item
import "reflect"
// GetItemMap get struct item with fieldK
func GetItemMap[K comparable, V any, Item any](values []Item, fieldK, fieldV string) map[K]V {
if len(values) == 0 {
return nil
}
res := make(map[K]V)
for _, v := range values {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
continue
}
rv = rv.Elem()
}
rk := rv.FieldByName(fieldK)
k, ok := rk.Interface().(K)
if !ok {
continue
}
rv1 := rv.FieldByName(fieldV)
value, ok := rv1.Interface().(V)
if !ok {
continue
}
res[k] = value
}
return res
}
// GetItemValues get struct item with fieldK
func GetItemValues[VT any, Item any](values []Item, fieldK string) []VT {
if len(values) == 0 {
return nil
}
res := make([]VT, 0)
for _, v := range values {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
continue
}
rv = rv.Elem()
}
rv1 := rv.FieldByName(fieldK)
value, ok := rv1.Interface().(VT)
if !ok {
continue
}
res = append(res, value)
}
return res
}