Skip to content

Commit 6d8f40c

Browse files
authored
Merge pull request #8500 from Roasbeef/fn-option-ergonomics
fn: add UnwrapOrErr and UnwrapOrFail to Option
2 parents 5a96026 + 166b2fd commit 6d8f40c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

fn/option.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package fn
22

3+
import "testing"
4+
35
// Option[A] represents a value which may or may not be there. This is very
46
// often preferable to nil-able pointers.
57
type Option[A any] struct {
@@ -54,6 +56,32 @@ func (o Option[A]) UnwrapOrFunc(f func() A) A {
5456
return ElimOption(o, f, func(a A) A { return a })
5557
}
5658

59+
// UnwrapOrFail is used to extract a value from an option within a test
60+
// context. If the option is None, then the test fails.
61+
func (o Option[A]) UnwrapOrFail(t *testing.T) A {
62+
t.Helper()
63+
64+
if o.isSome {
65+
return o.some
66+
}
67+
68+
t.Fatalf("Option[%T] was None()", o.some)
69+
70+
var zero A
71+
return zero
72+
}
73+
74+
// UnwrapOrErr is used to extract a value from an option, if the option is
75+
// empty, then the specified error is returned directly.
76+
func (o Option[A]) UnwrapOrErr(err error) (A, error) {
77+
if !o.isSome {
78+
var zero A
79+
return zero, err
80+
}
81+
82+
return o.some, nil
83+
}
84+
5785
// UnwrapOrFuncErr is used to extract a value from an option, and we supply a
5886
// thunk to be evaluated in the case when the Option is empty.
5987
func (o Option[A]) UnwrapOrFuncErr(f func() (A, error)) (A, error) {

0 commit comments

Comments
 (0)