forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalue.go
108 lines (93 loc) · 2 KB
/
value.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package reflects
import "reflect"
// Value struct
type Value struct {
reflect.Value
baseKind BKind
}
// Wrap the give value
func Wrap(rv reflect.Value) Value {
return Value{
Value: rv,
baseKind: ToBKind(rv.Kind()),
}
}
// ValueOf the give value
func ValueOf(v any) Value {
if rv, ok := v.(reflect.Value); ok {
return Wrap(rv)
}
rv := reflect.ValueOf(v)
return Value{
Value: rv,
baseKind: ToBKind(rv.Kind()),
}
}
// Indirect value. alias of the reflect.Indirect()
func (v Value) Indirect() Value {
if v.Kind() != reflect.Pointer {
return v
}
elem := v.Value.Elem()
return Value{
Value: elem,
baseKind: ToBKind(elem.Kind()),
}
}
// Elem returns the value that the interface v contains or that the pointer v points to.
//
// TIP: not like reflect.Value.Elem. otherwise, will return self.
func (v Value) Elem() Value {
if v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface {
elem := v.Value.Elem()
return Value{
Value: elem,
baseKind: ToBKind(elem.Kind()),
}
}
// otherwise, will return self
return v
}
// Type of value.
func (v Value) Type() Type {
return &xType{
Type: v.Value.Type(),
baseKind: v.baseKind,
}
}
// BKind value
func (v Value) BKind() BKind {
return v.baseKind
}
// BaseKind value
func (v Value) BaseKind() BKind {
return v.baseKind
}
// HasChild check. eg: array, slice, map, struct
func (v Value) HasChild() bool {
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.Map, reflect.Struct:
return true
}
return false
}
// Int value. if is uintX will convert to int64
func (v Value) Int() int64 {
switch v.baseKind {
case Uint:
return int64(v.Value.Uint())
case Int:
return v.Value.Int()
}
panic(&reflect.ValueError{Method: "reflect.Value.Int", Kind: v.Kind()})
}
// Uint value. if is intX will convert to uint64
func (v Value) Uint() uint64 {
switch v.baseKind {
case Uint:
return v.Value.Uint()
case Int:
return uint64(v.Value.Int())
}
panic(&reflect.ValueError{Method: "reflect.Value.Uint", Kind: v.Kind()})
}