Skip to content

Commit

Permalink
feat: added Unwrap, IsOk, IsErr (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
ColaFanta authored Nov 21, 2023
1 parent 0355d55 commit 749e1ca
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
15 changes: 15 additions & 0 deletions eh.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ func (r Result[T]) Eh() T {
return r.Ok
}

// IsOk returns true when result has no error and otherwise false
func (r Result[T]) IsOk() bool {
return r.Err == nil
}

// IsErr returns true when result has error and otherwise false
func (r Result[T]) IsErr() bool {
return r.Err != nil
}

// MustUnwrap returns the Ok value or panics if there is an error.
func (r Result[T]) MustUnwrap() T {
if r.Err != nil {
Expand All @@ -54,6 +64,11 @@ func (r Result[T]) MustUnwrapErr() error {
return r.Err
}

// Unwrap returns a value and an error
func (r Result[T]) Unwrap() (T, error) {
return r.Ok, r.Err
}

// ehError is used to wrap any errors that are raised because of calling
// ReturnIfErr on a Result.
type ehError struct {
Expand Down
4 changes: 2 additions & 2 deletions eh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,14 @@ func example(aFile string) (res Result[[]byte]) {

func TestExample(t *testing.T) {
res := example("README.md")
if res.Err != nil {
if res.IsErr() {
t.Fatalf("Err is not nil %+v", res)
}
}

func TestExampleFail(t *testing.T) {
res := example("non-existing-file")
if res.Err == nil {
if res.IsOk() {
t.Fatalf("Err should be nil %+v", res)
}
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/olevski/eh

go 1.20
go 1.21

0 comments on commit 749e1ca

Please sign in to comment.