-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstruct_provider.go
More file actions
48 lines (42 loc) · 991 Bytes
/
struct_provider.go
File metadata and controls
48 lines (42 loc) · 991 Bytes
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 transform
import "reflect"
type StructProvider struct {
rv reflect.Value
rt reflect.Type
}
func NewStructProvider(v interface{}) *StructProvider {
rv := Indirect(v)
if rv.Kind() != reflect.Struct {
panic(ErrTypeNotMatch)
}
return &StructProvider{
rv: rv,
rt: rv.Type(),
}
}
func (this *StructProvider) Set(f string, v interface{}) error {
rv := reflect.ValueOf(v)
rfv := this.rv.FieldByName(f)
if rfv.Kind() == reflect.Invalid {
return ErrFieldNotFound
}
if !rv.Type().AssignableTo(rfv.Type()) {
return ErrTypeNotMatch
}
rfv.Set(rv)
return nil
}
func (this *StructProvider) Get(f string) (interface{}, error) {
rfv := this.rv.FieldByName(f)
if rfv.Kind() == reflect.Invalid {
return nil, ErrFieldNotFound
}
return rfv.Interface(), nil
}
func (this *StructProvider) Fields() []string {
result := make([]string, 0, this.rt.NumField())
for i := 0; i < this.rt.NumField(); i++ {
result = append(result, this.rt.Field(i).Name)
}
return result
}