mirror of
https://github.com/lightningnetwork/lnd.git
synced 2025-01-19 05:45:21 +01:00
fn: add UnwrapOrErr and UnwrapOrFail to Option
In this commit, we add two new methods that simplify usage of an handling a value wrapped in an Option. Thes methods allow a caller to force the nil/None check up front, and either obtain the value, or fail the current execution or test. This should replace most usages of `UnsafeFromSome` where ever used today.
This commit is contained in:
parent
935e550da6
commit
166b2fdb97
28
fn/option.go
28
fn/option.go
@ -1,5 +1,7 @@
|
||||
package fn
|
||||
|
||||
import "testing"
|
||||
|
||||
// Option[A] represents a value which may or may not be there. This is very
|
||||
// often preferable to nil-able pointers.
|
||||
type Option[A any] struct {
|
||||
@ -54,6 +56,32 @@ func (o Option[A]) UnwrapOrFunc(f func() A) A {
|
||||
return ElimOption(o, f, func(a A) A { return a })
|
||||
}
|
||||
|
||||
// UnwrapOrFail is used to extract a value from an option within a test
|
||||
// context. If the option is None, then the test fails.
|
||||
func (o Option[A]) UnwrapOrFail(t *testing.T) A {
|
||||
t.Helper()
|
||||
|
||||
if o.isSome {
|
||||
return o.some
|
||||
}
|
||||
|
||||
t.Fatalf("Option[%T] was None()", o.some)
|
||||
|
||||
var zero A
|
||||
return zero
|
||||
}
|
||||
|
||||
// UnwrapOrErr is used to extract a value from an option, if the option is
|
||||
// empty, then the specified error is returned directly.
|
||||
func (o Option[A]) UnwrapOrErr(err error) (A, error) {
|
||||
if !o.isSome {
|
||||
var zero A
|
||||
return zero, err
|
||||
}
|
||||
|
||||
return o.some, nil
|
||||
}
|
||||
|
||||
// UnwrapOrFuncErr is used to extract a value from an option, and we supply a
|
||||
// thunk to be evaluated in the case when the Option is empty.
|
||||
func (o Option[A]) UnwrapOrFuncErr(f func() (A, error)) (A, error) {
|
||||
|
Loading…
Reference in New Issue
Block a user