-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmapx.go
51 lines (45 loc) · 928 Bytes
/
mapx.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
package mapx
import (
"errors"
"reflect"
)
var (
ErrNotAStruct = errors.New("mapx: provided value is not a struct")
ErrNotAPointer = errors.New("mapx: provided value is not a pointer")
)
func defaultTag(s string) string {
if s == "" {
return "mapx"
}
return s
}
func structFields[T any](tag string) fields {
typ := walkType(reflect.TypeOf((*T)(nil)).Elem())
if typ.Kind() == reflect.Struct {
return cachedFields(typeKey{
tag: defaultTag(tag),
Type: typ,
})
}
return nil
}
func fieldByIndex(v reflect.Value, index []int, alloc bool) reflect.Value {
if len(index) == 1 {
return v.Field(index[0])
}
for i, x := range index {
if i > 0 {
if v.Kind() == reflect.Pointer && v.Type().Elem().Kind() == reflect.Struct {
if v.IsNil() {
if !alloc {
return reflect.Value{}
}
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
}
v = v.Field(x)
}
return v
}