-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
structs.go
64 lines (56 loc) · 1.22 KB
/
structs.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
package namedstruct
import (
"fmt"
"reflect"
)
func NewStructs() *Structs {
return &Structs{
types: map[string]reflect.Type{},
}
}
type Structs struct {
types map[string]reflect.Type
}
func (s *Structs) Register(name string, v interface{}) {
_, ok := s.GetType(name)
if ok {
panic(fmt.Sprintf(`%v: name=%s, type=%T`, ErrNameConflict, name, v))
}
s.types[name] = reflect.ValueOf(v).Type()
}
func (s *Structs) MakeSlice(name string) interface{} {
typ, ok := s.GetType(name)
if !ok {
return nil
}
sliceType := reflect.SliceOf(typ)
return reflect.New(sliceType).Interface()
}
func (s *Structs) GetType(name string) (reflect.Type, bool) {
typ, ok := s.types[name]
return typ, ok
}
func (s *Structs) Make(name string) interface{} {
typ, ok := s.GetType(name)
if !ok {
return nil
}
if typ.Kind() == reflect.Ptr {
return reflect.New(typ.Elem()).Interface()
}
return reflect.New(typ).Interface()
}
func ConvertToSlice(recv interface{}) []interface{} {
v := reflect.ValueOf(recv)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Slice {
return nil
}
results := make([]interface{}, v.Len())
for i, j := 0, v.Len(); i < j; i++ {
results[i] = v.Index(i).Interface()
}
return results
}