/
structutils.go
62 lines (56 loc) · 1.19 KB
/
structutils.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
package sutil
import (
"reflect"
"github.com/fatih/structs"
)
func FieldNames(t reflect.Type) []string {
n := t.NumField()
r := make([]string, n)
for i := 0; i < n; i++ {
r[i] = t.Field(i).Name
}
return r
}
func Copy(src, dst interface{}) {
s := structs.New(src)
d := structs.New(dst)
sm := make(map[string]*structs.Field)
for _, f := range s.Fields() {
sm[f.Name()] = f
}
for _, d := range d.Fields() {
if f, ok := sm[d.Name()]; ok {
d.Set(f.Value())
}
}
}
func Get(v interface{}, field string) interface{} {
vV := PtrValue(reflect.ValueOf(v))
return vV.FieldByName(field).Interface()
}
func PtrType(t reflect.Type) reflect.Type {
if reflect.Ptr == t.Kind() {
return PtrType(t.Elem())
}
return t
}
func PtrValue(v reflect.Value) reflect.Value {
if reflect.Ptr == v.Kind() {
return PtrValue(v.Elem())
}
return v
}
func Ptr(a interface{}) interface{} {
return PtrValue(reflect.ValueOf(a)).Interface()
}
// func Struct2Map(a interface{}) map[string]interface{} {
// return structs.Map(a)
// }
func MapGet(m interface{}, key interface{}) interface{} {
mV := reflect.ValueOf(m)
r := mV.MapIndex(reflect.ValueOf(key))
if !r.IsValid() {
return nil
}
return r.Interface()
}