forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
value.go
142 lines (120 loc) · 2.09 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package structs
import (
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/mathutil"
"github.com/gookit/goutil/strutil"
)
// Value data store
type Value struct {
// V value
V any
}
// NewValue instance.
func NewValue(val any) *Value {
return &Value{
V: val,
}
}
// Set value
func (v *Value) Set(val any) {
v.V = val
}
// Reset value
func (v *Value) Reset() {
v.V = nil
}
// Val get
func (v *Value) Val() any {
return v.V
}
// Int value get
func (v *Value) Int() int {
if v.V == nil {
return 0
}
return mathutil.QuietInt(v.V)
}
// Int64 value
func (v *Value) Int64() int64 {
if v.V == nil {
return 0
}
return mathutil.QuietInt64(v.V)
}
// Bool value
func (v *Value) Bool() bool {
if v.V == nil {
return false
}
if bl, ok := v.V.(bool); ok {
return bl
}
if str, ok := v.V.(string); ok {
return strutil.QuietBool(str)
}
return false
}
// Float64 value
func (v *Value) Float64() float64 {
if v.V == nil {
return 0
}
return mathutil.QuietFloat(v.V)
}
// String value
func (v *Value) String() string {
if v.V == nil {
return ""
}
if str, ok := v.V.(string); ok {
return str
}
return strutil.QuietString(v.V)
}
// Strings value
func (v *Value) Strings() (ss []string) {
if v.V == nil {
return
}
if ss, ok := v.V.([]string); ok {
return ss
}
if str, ok := v.V.(string); ok {
return strutil.Split(str, comdef.DefaultSep)
}
return
}
// SplitToStrings split string value to strings
func (v *Value) SplitToStrings(sep ...string) (ss []string) {
if v.V == nil {
return
}
if str, ok := v.V.(string); ok {
return strutil.Split(str, sepStr(sep))
}
return
}
// SplitToInts split string value to []int
func (v *Value) SplitToInts(sep ...string) (ss []int) {
if v.V == nil {
return
}
if str, ok := v.V.(string); ok {
ints, err := arrutil.StringsToInts(strutil.Split(str, sepStr(sep)))
if err == nil {
return ints
}
}
return
}
// IsEmpty value
func (v *Value) IsEmpty() bool {
return v.V == nil
}
func sepStr(seps []string) string {
if len(seps) > 0 {
return seps[0]
}
return comdef.DefaultSep
}