-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheither.go
More file actions
73 lines (59 loc) · 1.59 KB
/
either.go
File metadata and controls
73 lines (59 loc) · 1.59 KB
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
package fun
import (
"errors"
)
// Either represents one of two possible results.
type Either[L, R any] struct {
isLeft bool
left L
right R
}
// NewEither builds a new Either object.
//
// Note: Considered an internal implementation.
// Prefer using either.Left() or either.Right().
func NewEither[L, R any](isLeft bool, left L, right R) Either[L, R] {
return Either[L, R]{
isLeft: isLeft,
left: left,
right: right,
}
}
// IsLeft tells you if the object has a Left value.
func (e Either[L, R]) IsLeft() bool {
return e.isLeft
}
// Left gets the left value of the either.
func (e Either[L, R]) Left() L {
return e.left
}
// ErrMissingLeftValue represents a failure to extract a Left value from an Either.
var ErrMissingLeftValue = errors.New("either had no left value")
// RequireLeft gets the left value of the either or panics.
func (e Either[L, R]) RequireLeft() L {
if !e.IsLeft() {
panic(ErrMissingLeftValue)
}
return e.left
}
// IsRight tells you if the object has a Right value.
func (e Either[L, R]) IsRight() bool {
return !e.isLeft
}
// Right gets the right value of the either.
func (e Either[L, R]) Right() R {
return e.right
}
// ErrMissingRightValue represents a failure to extract a Right value from an Either.
var ErrMissingRightValue = errors.New("either had no right value")
// RequireRight gets the right value of the either or panics.
func (e Either[L, R]) RequireRight() R {
if !e.IsRight() {
panic(ErrMissingRightValue)
}
return e.right
}
// Tuple returns both values regardless of the type.
func (e Either[L, R]) Tuple() (L, R) {
return e.left, e.right
}