-
Notifications
You must be signed in to change notification settings - Fork 0
/
goptional.go
67 lines (51 loc) · 945 Bytes
/
goptional.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
package goptional
type optional[T any] struct {
val *T
}
func None[T any]() optional[T] {
return optional[T]{}
}
func Some[T any](val T) optional[T] {
return optional[T]{
val: &val,
}
}
func Of[T any](val *T) optional[T] {
if val == nil {
return None[T]()
}
return Some[T](*val)
}
func (o optional[T]) IsPresent() bool {
return nil != o.val
}
func (o optional[T]) IsEmpty() bool {
return !o.IsPresent()
}
func (o optional[T]) Get() (T, bool) {
if o.IsPresent() {
return *o.val, true
}
return *new(T), false //nolint: gocritic
}
func (o optional[T]) GetOr(emptyValue T) T {
if val, ok := o.Get(); ok {
return val
}
return emptyValue
}
func (o optional[T]) GetOrZero() T {
val, _ := o.Get()
return val
}
func (o optional[T]) GetOrPanic() T {
if val, ok := o.Get(); ok {
return val
}
panic("not present")
}
func (o optional[T]) IfPresent(consumer func(T)) {
if o.IsPresent() {
consumer(*o.val)
}
}