-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathoptional.go
62 lines (53 loc) · 1011 Bytes
/
optional.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
package control
import (
"fmt"
"reflect"
)
type Optional[T any] struct {
value T
err error
}
func optional[T any](value any, err error) Optional[T] {
var nilValue T
if err != nil {
return Optional[T]{err: err}
}
if value == nil {
return Optional[T]{}
}
switch typed := value.(type) {
case T:
return Optional[T]{value: typed}
default:
return Optional[T]{err: fmt.Errorf("can't cast %s to %s", reflect.TypeOf(value), reflect.TypeOf(nilValue))}
}
}
func (op Optional[T]) Unwrap() (T, error) {
return op.value, op.err
}
func (op Optional[T]) Err() error {
return op.err
}
func (op Optional[T]) MustGetValue() T {
if op.err != nil {
panic(op.err)
}
return op.value
}
func (op Optional[T]) Then(f func(T) error) error {
if op.err == nil {
return f(op.value)
}
return op.err
}
func (op Optional[T]) Catch(f func(error) error) error {
if op.err != nil {
return f(op.err)
}
return nil
}
func (op Optional[T]) IfPresent(f func(T)) {
if op.err == nil {
f(op.value)
}
}