-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
74 lines (61 loc) · 1.3 KB
/
options.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
package utils
import "reflect"
type Options[T any] struct {
values T
none bool
}
type OptionInterface[T any] interface {
IsSome() bool
IsNone() bool
Unwrap() T
Expect(msg string) T
UnwrapOr(defaultValue T) T
IsSomeAnd(fn func(args ...interface{}) bool) bool
Inspect() Options[T]
}
func Some[T any](value T) Options[T] {
return Options[T]{values: value, none: reflect.ValueOf(value).IsZero()}
}
func None[T any]() Options[T] {
return Options[T]{none: true}
}
func (o Options[T]) IsSome() bool {
return !o.none
}
func (o Options[T]) IsNone() bool {
return o.none
}
func (o Options[T]) Unwrap() T {
if o.none {
panic("Unwrap: Option is None")
}
return o.values
}
func (o Options[T]) Expect(msg string) T {
if o.none {
panic("Expect: " + msg)
}
return o.values
}
func (o Options[T]) UnwrapOr(defaultValue any) any {
if o.none {
return defaultValue
}
return o.values
}
func (o Options[T]) IsSomeAnd(fn func(args ...interface{}) bool) bool {
if o.none {
return false
}
return fn(o.values)
}
func (o Options[T]) Inspect() Options[T] {
return o
}
func Option[T any](value T) Options[T] {
if(&value == nil){
return None[T]()
}else{
return Some[T](value)
}
}