From 984aae25535830073d41a3e0ac6324ae0ff7d8a4 Mon Sep 17 00:00:00 2001 From: milarin Date: Sat, 25 Mar 2023 11:12:36 +0100 Subject: [PATCH] Result implemented --- result.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 result.go diff --git a/result.go b/result.go new file mode 100644 index 0000000..87d4feb --- /dev/null +++ b/result.go @@ -0,0 +1,50 @@ +package channel + +type Result[T any] struct { + value *T + err error +} + +func ResultOf[T any](value T, err error) Result[T] { + if err != nil { + return Result[T]{value: nil, err: err} + } + + return Result[T]{value: &value, err: nil} +} + +func WrapMapFunc[I, O any](f func(I) (O, error)) func(I) Result[O] { + return func(i I) Result[O] { return ResultOf(f(i)) } +} + +func WrapMapResultFunc[I, O any](f func(I) (O, error)) func(Result[I]) Result[O] { + resFunc := WrapMapFunc(f) + nilValue := *new(O) + return func(r Result[I]) Result[O] { + v, err := r.Get() + if err != nil { + return ResultOf(nilValue, err) + } + return resFunc(v) + } +} + +func (r Result[T]) Success() bool { + return r.err == nil +} + +func (r Result[T]) Fail() bool { + return !r.Success() +} + +func (r Result[T]) GetOrDefault(defaultValue T) T { + if r.Fail() { + return defaultValue + } + + return *r.value +} + +func (r Result[T]) Get() (T, error) { + return *r.value, r.err +}