forked from reiver/go-cast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbool.go
57 lines (51 loc) · 1.02 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
package cast
// Bool will return a bool when `v` is of type bool, or has a method:
//
// type interface {
// Bool() (bool, error)
// }
//
// ... that returns successfully.
//
// Else it will return an error.
func Bool(v interface{}) (bool, error) {
switch value := v.(type) {
case bool:
return value, nil
case int8:
return value != 0, nil
case int16:
return value != 0, nil
case int32:
return value != 0, nil
case int64:
return value != 0, nil
case uint8:
return value != 0, nil
case uint16:
return value != 0, nil
case uint32:
return value != 0, nil
case uint64:
return value != 0, nil
case float32:
return value != 0, nil
case float64:
return value != 0, nil
case booler:
return value.Bool()
default:
return false, internalCannotCastComplainer{expectedType:"bool", actualType:typeof(value)}
}
}
// MustBool is like Bool, expect panic()s on an error.
func MustBool(v interface{}) bool {
x, err := Bool(v)
if nil != err {
panic(err)
}
return x
}
type booler interface {
Bool() (bool, error)
}