-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbool.go
46 lines (39 loc) · 882 Bytes
/
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
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 any) (bool, error) {
switch value := v.(type) {
case bool:
return bool(value), nil
case booler:
return value.Bool()
default:
return false, internalCannotCastComplainer{expectedType:"bool", actualType:typeof(value)}
}
}
// BoolElse is similar to [Bool] except that if a cast cannot be done, it returns the `alternative`.
func BoolElse(v any, alternative bool) bool {
result, err := Bool(v)
if nil != err {
return alternative
}
return result
}
// MustBool is like Bool, expect panic()s on an error.
func MustBool(v any) bool {
x, err := Bool(v)
if nil != err {
panic(err)
}
return x
}
type booler interface {
Bool() (bool, error)
}