Skip to content

Commit

Permalink
result: add Unpack (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
phelmkamp authored May 7, 2022
1 parent 4f97248 commit 43493b1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
7 changes: 7 additions & 0 deletions result/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package result
import (
"errors"
"fmt"

"github.com/phelmkamp/valor/optional"
)

Expand Down Expand Up @@ -71,6 +72,12 @@ func (res Result[T]) String() string {
return fmt.Sprintf("{%v %v}", res.v, res.err)
}

// Unpack returns the underlying value and error.
// This aids in assigning to variables or function arguments.
func (res Result[T]) Unpack() (T, error) {
return res.v, res.err
}

// Value returns an optional.Value containing either the
// underlying value or nothing.
func (res Result[T]) Value() optional.Value[T] {
Expand Down
16 changes: 13 additions & 3 deletions result/result_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ package result_test
import (
"errors"
"fmt"
"github.com/phelmkamp/valor/optional"
"github.com/phelmkamp/valor/result"
"github.com/phelmkamp/valor/tuple/unit"
"io"
"io/fs"
"reflect"
"strconv"
"strings"
"testing"

"github.com/phelmkamp/valor/optional"
"github.com/phelmkamp/valor/result"
"github.com/phelmkamp/valor/tuple/unit"
)

// type checks
Expand Down Expand Up @@ -258,3 +259,12 @@ func TestResult_OfError(t *testing.T) {
t.Errorf("OfError() = %v, want %v", got, result.OfError[float64](nil))
}
}

func TestResult_Unpack(t *testing.T) {
if v, err := result.OfError[string](errFail).Unpack(); v != "" || err != errFail {
t.Errorf("Unpack() = %v %v, want %v %v", v, err, "", errFail)
}
if v, err := result.OfOk("foo").Unpack(); v != "foo" || err != nil {
t.Errorf("Unpack() = %v %v, want %v %v", v, err, "foo", nil)
}
}
2 changes: 1 addition & 1 deletion tuple/two/two_tuple.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TupleResultOf[T, T2 any](v T, v2 T2, err error) result.Result[Tuple[T, T2]]
// TupleMap returns a Tuple with each value replaced by the result of each function.
//
// funcs.Ident can be used to leave the value unchanged.
func TupleMap[Tp, T2p, T, T2 any](t Tuple[T, T2], f func(T) Tp, f2 func(T2) T2p) (tp Tuple[Tp, T2p]) {
func TupleMap[T, T2, Tp, T2p any](t Tuple[T, T2], f func(T) Tp, f2 func(T2) T2p) (tp Tuple[Tp, T2p]) {
return TupleOf(f(t.V), f2(t.V2))
}

Expand Down

0 comments on commit 43493b1

Please sign in to comment.