From 749e1ca4c745d549ec2a83e7448afc6f6e94180f Mon Sep 17 00:00:00 2001 From: ColaFanta <44313748+ColaFanta@users.noreply.github.com> Date: Tue, 21 Nov 2023 20:11:42 +0800 Subject: [PATCH] feat: added Unwrap, IsOk, IsErr (#1) --- eh.go | 15 +++++++++++++++ eh_test.go | 4 ++-- go.mod | 2 +- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/eh.go b/eh.go index 1943ceb..283c082 100644 --- a/eh.go +++ b/eh.go @@ -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 { @@ -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 { diff --git a/eh_test.go b/eh_test.go index 27f8e9a..a31b62f 100644 --- a/eh_test.go +++ b/eh_test.go @@ -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) } } diff --git a/go.mod b/go.mod index d0b131a..96a32e7 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/olevski/eh -go 1.20 +go 1.21