This repository has been archived by the owner on Apr 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
102 lines (89 loc) · 1.7 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
99
100
101
102
package result
type Option[T any] struct {
value *T
}
func (opt Option[T]) IsNone() bool {
return opt.value == nil
}
func (opt Option[T]) IsSome() bool {
return opt.value != nil
}
func (opt Option[T]) IsSomeAnd(f func(value T) bool) bool {
if opt.IsNone() {
return false
}
return f(*opt.value)
}
func (opt Option[T]) OkOr(err error) Result[T] {
if opt.IsSome() {
return Ok(*opt.value)
}
return Err[T](err)
}
func (opt Option[T]) OkOrElse(err func() error) Result[T] {
if opt.IsSome() {
return Ok(*opt.value)
}
return Err[T](err())
}
func (opt Option[T]) Expect(msg string) T {
if opt.IsSome() {
return *opt.value
}
panic(msg)
}
func (opt Option[T]) Filter(predicate func(value T) bool) Option[T] {
if opt.IsSome() {
if predicate(*opt.value) {
return Some(*opt.value)
}
}
return None[T]()
}
// func (opt *Option[T]) Flatten() {
// }
func (opt Option[T]) Unwrap() T {
if opt.IsSome() {
return *opt.value
}
panic("called `Option.unwrap()` on a `None` value")
}
func (opt Option[T]) UnwrapOr(value T) T {
if opt.IsSome() {
return *opt.value
}
return value
}
func (opt Option[T]) UnwrapOrDefault() T {
var value T
return value
}
func (opt Option[T]) UnwrapOrElse(f func() T) T {
if opt.IsSome() {
return *opt.value
}
return f()
}
func (opt Option[T]) Or(value Option[T]) Option[T] {
if opt.IsSome() {
return Some(*opt.value)
}
return value
}
func (opt Option[T]) OrElse(f func() Option[T]) Option[T] {
if opt.IsSome() {
return Some(*opt.value)
}
return f()
}
func (opt Option[T]) Cloned() Option[T] {
return Option[T]{value: opt.value}
}
func Some[T any](value T) Option[T] {
return Option[T]{
value: &value,
}
}
func None[T any]() Option[T] {
return Option[T]{}
}