forked from Ompluscator/dynamic-struct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter_struct.go
79 lines (71 loc) · 1.61 KB
/
writer_struct.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package dynamicstruct
import (
"errors"
"reflect"
"strings"
)
type structImpl struct {
fields map[string]Writer
value reflect.Value
field reflect.Type
}
func (s *structImpl) Set(value any) (err error) {
defer func() {
er := recover()
if er != nil {
err = errors.New(er.(string))
}
}()
s.value.Set(reflect.ValueOf(value))
return
}
func (s *structImpl) Get() (any, bool) {
return s.value.Interface(), true
}
// can set struct.substruct field value
func (s *structImpl) linkSet(names []string, value any) error {
if len(names) == 0 {
return s.Set(value)
}
name := names[0]
field, ok := s.fields[name]
if !ok {
return errors.New("not found field " + name)
}
return field.linkSet(names[1:], value)
}
func (s *structImpl) LinkSet(linkName string, value any) error {
return s.linkSet(strings.Split(linkName, SqliteSeq), value)
}
func (s *structImpl) LinkGet(linkName string) (any, bool) {
return s.linkGet(strings.Split(linkName, SqliteSeq))
}
// can set struct.substruct field value
func (s *structImpl) linkGet(names []string) (any, bool) {
if len(names) == 0 {
return s.Get()
}
name := names[0]
field, ok := s.fields[name]
if !ok {
return nil, false
}
return field.linkGet(names[1:])
}
func (s *structImpl) Type() reflect.Type {
return s.field
}
func (s *structImpl) linkTyp(names []string) (reflect.Type, bool) {
if len(names) == 0 {
return s.Type(), true
}
name := names[0]
field, ok := s.fields[name]
if !ok {
return nil, false
}
return field.linkTyp(names[1:])
}
func (s *structImpl) LinkTyp(name string) (reflect.Type, bool) {
return s.linkTyp(strings.Split(name, SqliteSeq))
}