-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
52 lines (42 loc) · 836 Bytes
/
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
package option
import "fmt"
type Option[T any] struct {
x *T
}
func (opt Option[T]) IsSome() bool {
return opt.x != nil
}
func (opt Option[T]) ToString() string {
if opt.IsSome() {
return fmt.Sprintf("Some(%v)", opt.Unwrap())
} else {
return "None"
}
}
func (opt Option[T]) Unwrap() T {
return *opt.x
}
// UnwrapOr returns the wrapped value or the default value <defa>
func (opt Option[T]) UnwrapOr(defa T) T {
if opt.x == nil {
return defa
}
return *opt.x
}
func (opt *Option[T]) Replace(x T) {
opt.x = &x
}
func Fmap[T any, R any](opt Option[T], f func(x T) R) Option[R] {
if opt.IsSome() {
var y R = f(opt.Unwrap())
return Option[R]{x: &y}
} else {
return Option[R]{x: nil}
}
}
func Some[T any](x T) Option[T] {
return Option[T]{x: &x}
}
func None[T any]() Option[T] {
return Option[T]{x: nil}
}