File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 11package 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.
57type 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.
5987func (o Option [A ]) UnwrapOrFuncErr (f func () (A , error )) (A , error ) {
You can’t perform that action at this time.
0 commit comments