@@ -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.
1423func 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.
3751func (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] {
140154func 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