mirror of
https://github.com/lightningnetwork/lnd.git
synced 2025-02-23 06:35:07 +01:00
Merge pull request #8853 from Roasbeef/result-utils
fn: add additional utility methods for Result[T]
This commit is contained in:
commit
376b8cedc4
1 changed files with 26 additions and 0 deletions
26
fn/result.go
26
fn/result.go
|
@ -10,6 +10,15 @@ type Result[T any] struct {
|
||||||
Either[T, error]
|
Either[T, error]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewResult creates a new result from a (value, error) tuple.
|
||||||
|
func NewResult[T any](val T, err error) Result[T] {
|
||||||
|
if err != nil {
|
||||||
|
return Err[T](err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(val)
|
||||||
|
}
|
||||||
|
|
||||||
// Ok creates a new Result with a success value.
|
// Ok creates a new Result with a success value.
|
||||||
func Ok[T any](val T) Result[T] {
|
func Ok[T any](val T) Result[T] {
|
||||||
return Result[T]{Either: NewLeft[T, error](val)}
|
return Result[T]{Either: NewLeft[T, error](val)}
|
||||||
|
@ -33,6 +42,11 @@ func (r Result[T]) Unpack() (T, error) {
|
||||||
return r.left.UnwrapOr(zero), r.right.UnwrapOr(nil)
|
return r.left.UnwrapOr(zero), r.right.UnwrapOr(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Err exposes the underlying error of the result type as a normal error type.
|
||||||
|
func (r Result[T]) Err() error {
|
||||||
|
return r.right.some
|
||||||
|
}
|
||||||
|
|
||||||
// IsOk returns true if the Result is a success value.
|
// IsOk returns true if the Result is a success value.
|
||||||
func (r Result[T]) IsOk() bool {
|
func (r Result[T]) IsOk() bool {
|
||||||
return r.IsLeft()
|
return r.IsLeft()
|
||||||
|
@ -140,3 +154,15 @@ func FlatMap[A, B any](r Result[A], f func(A) Result[B]) Result[B] {
|
||||||
func AndThen[A, B any](r Result[A], f func(A) Result[B]) Result[B] {
|
func AndThen[A, B any](r Result[A], f func(A) Result[B]) Result[B] {
|
||||||
return FlatMap(r, f)
|
return FlatMap(r, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AndThen2 applies a function that returns a Result[C] to the success values
|
||||||
|
// of two Result types if both exist.
|
||||||
|
func AndThen2[A, B, C any](ra Result[A], rb Result[B],
|
||||||
|
f func(A, B) Result[C]) Result[C] {
|
||||||
|
|
||||||
|
return AndThen(ra, func(a A) Result[C] {
|
||||||
|
return AndThen(rb, func(b B) Result[C] {
|
||||||
|
return f(a, b)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue