-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
98 lines (78 loc) · 2.13 KB
/
option.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package option
import "fmt"
// Option represents an optional value. The [Some] variant contains a value and
// the [None] variant represents the absence of a value.
type Option[T any] struct {
value T
present bool
}
// Some instantiates an [Option] with a value.
func Some[T any](value T) Option[T] {
return Option[T]{value, true}
}
// None instantiates an [Option] with no value.
func None[T any]() Option[T] {
return Option[T]{}
}
// String implements the [fmt.Stringer] interface.
func (o Option[T]) String() string {
if o.present {
return fmt.Sprintf("Some(%v)", o.value)
}
return "None"
}
var _ fmt.Stringer = Option[struct{}]{}
// Unwrap returns the underlying value of a [Some] variant, or panics if called
// on a [None] variant.
func (o Option[T]) Unwrap() T {
if o.present {
return o.value
}
panic("called `Option.Unwrap()` on a `None` value")
}
// UnwrapOr returns the underlying value of a [Some] variant, or the provided
// value on a [None] variant.
func (o Option[T]) UnwrapOr(value T) T {
if o.present {
return o.value
}
return value
}
// UnwrapOrElse returns the underlying value of a [Some] variant, or the result
// of calling the provided function on a [None] variant.
func (o Option[T]) UnwrapOrElse(f func() T) T {
if o.present {
return o.value
}
return f()
}
// UnwrapOrZero returns the underlying value of a [Some] variant, or the zero
// value on a [None] variant.
func (o Option[T]) UnwrapOrZero() T {
if o.present {
return o.value
}
var value T
return value
}
// IsSome returns true if the [Option] is a [Some] variant.
func (o Option[T]) IsSome() bool {
return o.present
}
// IsNone returns true if the [Option] is a [None] variant.
func (o Option[T]) IsNone() bool {
return !o.present
}
// Value returns the underlying value and true for a [Some] variant, or the
// zero value and false for a [None] variant.
func (o Option[T]) Value() (T, bool) {
return o.value, o.present
}
// Expect returns the underlying value for a [Some] variant, or panics with the
// provided message for a [None] variant.
func (o Option[T]) Expect(message string) T {
if o.present {
return o.value
}
panic(message)
}