-
Notifications
You must be signed in to change notification settings - Fork 0
/
field_info.go
45 lines (40 loc) · 1.04 KB
/
field_info.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
package reflectx
import (
"errors"
"reflect"
)
// FieldInfo : field info
type FieldInfo struct {
Name string
Type reflect.Type
Kind reflect.Kind
Tags reflect.StructTag
}
// SetValue : set value to field, field must be kind of reflect.Ptr
func (field FieldInfo) SetValue(instance interface{}, v interface{}) {
val := reflect.ValueOf(instance)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
vField := val.FieldByName(field.Name)
if vField.CanSet() {
vField.Set(reflect.ValueOf(v))
}
}
// GetValue : get value of field
func (field FieldInfo) GetValue(instance interface{}) interface{} {
val := reflect.ValueOf(instance)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
vField := val.FieldByName(field.Name)
//return field.Value.Interface()
return vField.Interface()
}
// AsTypeInfo : convert field to TypeInfo
func (field FieldInfo) AsTypeInfo() (TypeInfo, error) {
if field.Kind == reflect.Struct || field.Kind == reflect.Ptr {
return GetTypeInfoWithValueType(field.Type)
}
return TypeInfo{}, errors.New("must be struct")
}