-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.go
105 lines (101 loc) · 1.55 KB
/
bool.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
package cast
import (
"strconv"
)
// Booler is the interface that wraps the Bool method.
// Bool method return bool
type Booler interface {
Bool() bool
}
//Bool cast input to bool
func Bool(input interface{}) (output bool, err error) {
switch castValue := input.(type) {
case Booler:
output = castValue.Bool()
return
case string:
var errParse error
output, errParse = strconv.ParseBool(castValue)
if errParse != nil && len(castValue) > 0 {
output = true
}
return
case int:
if castValue != 0 {
output = true
}
return
case int8:
if castValue != 0 {
output = true
}
return
case int16:
if castValue != 0 {
output = true
}
return
case int32:
if castValue != 0 {
output = true
}
return
case int64:
if castValue != 0 {
output = true
}
return
case uint:
if castValue != 0 {
output = true
}
return
case uint8:
if castValue != 0 {
output = true
}
return
case uint16:
if castValue != 0 {
output = true
}
return
case uint32:
if castValue != 0 {
output = true
}
return
case uint64:
if castValue != 0 {
output = true
}
return
case float32:
if castValue != 0 {
output = true
}
return
case float64:
if castValue != 0 {
output = true
}
return
case bool:
output = castValue
return
case nil:
output = false
return
default:
err = NewCastError("Could not convert to bool")
}
return
}
//MustBool cast input to bool and panic if error
func MustBool(input interface{}) bool {
output, err := Bool(input)
if err != nil {
panic(err)
}
return output
}