-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreflect.go
More file actions
72 lines (65 loc) · 1.69 KB
/
reflect.go
File metadata and controls
72 lines (65 loc) · 1.69 KB
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
package g
import (
"reflect"
"strings"
)
// StructField is a field of a struct
type StructField struct {
Field reflect.StructField
Value reflect.Value
JKey string
}
// IsPointer returns `true` is obj is a pointer
func IsPointer(obj interface{}) bool {
value := reflect.ValueOf(obj)
return value.Kind() == reflect.Ptr
}
// IsSlice returns `true` is obj is a slice
func IsSlice(obj interface{}) bool {
value := reflect.ValueOf(obj)
return value.Kind() == reflect.Slice || value.Kind() == reflect.Array
}
// StructFieldsMapToKey returns a map of fields name to key
func StructFieldsMapToKey(obj interface{}) (m map[string]string) {
m = map[string]string{}
for _, f := range StructFields(obj) {
m[f.Field.Name] = f.JKey
m[f.JKey] = f.JKey
}
return
}
// StructFields returns the fields of a struct
func StructFields(obj interface{}) (fields []StructField) {
var t reflect.Type
value := reflect.ValueOf(obj)
if value.Kind() == reflect.Ptr {
t = reflect.Indirect(value).Type()
} else {
t = reflect.TypeOf(obj)
}
for i := 0; i < t.NumField(); i++ {
var valueField reflect.Value
if value.Kind() == reflect.Ptr {
valueField = value.Elem().Field(i)
} else {
valueField = value.Field(i)
}
sField := t.Field(i)
jKey := strings.Split(sField.Tag.Get("json"), ",")[0]
fields = append(fields, StructField{sField, valueField, jKey})
}
return fields
}
// CloneValue clones a pointer to another
func CloneValue(source interface{}, destin interface{}) {
x := reflect.ValueOf(source)
if x.Kind() == reflect.Ptr {
starX := x.Elem()
y := reflect.New(starX.Type())
starY := y.Elem()
starY.Set(starX)
reflect.ValueOf(destin).Elem().Set(y.Elem())
} else {
destin = x.Interface()
}
}