Skip to content

Commit f1a3871

Browse files
committed
fn: add additional utility methods for Result[T]
`NewResult` makes it easy to wrap a normal function call in a result value. `Err` can be used to check the error case of the result without unpacking the entire thing. `AndThen2` allows a caller to compose a function on two results values, with the closure only executing if both values are non-error.
1 parent 390f072 commit f1a3871

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

fn/result.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,15 @@ type Result[T any] struct {
1010
Either[T, error]
1111
}
1212

13+
// NewResult creates a new result from a (value, error) tuple.
14+
func NewResult[T any](val T, err error) Result[T] {
15+
if err != nil {
16+
return Err[T](err)
17+
}
18+
19+
return Ok(val)
20+
}
21+
1322
// Ok creates a new Result with a success value.
1423
func Ok[T any](val T) Result[T] {
1524
return Result[T]{Either: NewLeft[T, error](val)}
@@ -33,6 +42,11 @@ func (r Result[T]) Unpack() (T, error) {
3342
return r.left.UnwrapOr(zero), r.right.UnwrapOr(nil)
3443
}
3544

45+
// Err exposes the underlying error of the result type as a normal error type.
46+
func (r Result[T]) Err() error {
47+
return r.right.some
48+
}
49+
3650
// IsOk returns true if the Result is a success value.
3751
func (r Result[T]) IsOk() bool {
3852
return r.IsLeft()
@@ -140,3 +154,15 @@ func FlatMap[A, B any](r Result[A], f func(A) Result[B]) Result[B] {
140154
func AndThen[A, B any](r Result[A], f func(A) Result[B]) Result[B] {
141155
return FlatMap(r, f)
142156
}
157+
158+
// AndThen2 applies a function that returns a Result[C] to the success values
159+
// of two Result types if both exist.
160+
func AndThen2[A, B, C any](ra Result[A], rb Result[B],
161+
f func(A, B) Result[C]) Result[C] {
162+
163+
return AndThen(ra, func(a A) Result[C] {
164+
return AndThen(rb, func(b B) Result[C] {
165+
return f(a, b)
166+
})
167+
})
168+
}

0 commit comments

Comments
 (0)