-
Notifications
You must be signed in to change notification settings - Fork 32
/
field.go
48 lines (41 loc) · 955 Bytes
/
field.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
package underscore
import (
"reflect"
"strings"
)
// GetFieldValueFunc is get field reflect.Value func
type GetFieldValueFunc func(interface{}) reflect.Value
// Field is 获取字段函数
func Field(name string) func(interface{}) interface{} {
fn := FieldValue(name)
return func(item interface{}) interface{} {
return fn(item).Interface()
}
}
// FieldValue is 获取reflect.Value
func FieldValue(name string) GetFieldValueFunc {
var getter GetFieldValueFunc
getter = func(item interface{}) reflect.Value {
itemRV := getRealValue(item)
if itemRV.Kind() == reflect.Ptr {
itemRV = itemRV.Elem()
}
itemRT := itemRV.Type()
for i := 0; i < itemRT.NumField(); i++ {
field := itemRT.Field(i)
if field.Anonymous {
rv := getter(
itemRV.Field(i),
)
if rv != nilValue {
return rv
}
}
if strings.EqualFold(name, field.Name) {
return itemRV.Field(i)
}
}
return nilValue
}
return getter
}