blob: 29e3dc70c790bcd1578d82b966a911ce7b39beb0 (
plain)
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
|
package common
import "reflect"
type Opt[T any] interface {
OrElse(thing T) T
}
type OptError[T any] struct {
thing T
err error
}
type OptNull[T any] struct {
ptr *T
}
type OptZero[T any] struct {
thing T
}
func (o OptNull[T]) OrElse(thing T) T {
if o.ptr != nil {
return *o.ptr
}
return thing
}
func Errorable[T any](thing T, err error) Opt[T] {
return OptError[T]{
thing: thing,
err: err,
}
}
func (o OptError[T]) OrElse(thing T) T {
if o.err != nil {
return thing
}
return o.thing
}
func Nullable[T any](ptr *T) Opt[T] {
return OptNull[T]{
ptr: ptr,
}
}
func Zeroable[T any](thing T) Opt[T] {
return OptZero[T]{
thing: thing,
}
}
func (o OptZero[T]) OrElse(thing T) T {
var zero T
if reflect.DeepEqual(zero, o.thing) {
return thing
}
return o.thing
}
|