diff --git a/.gitignore b/.gitignore index 3b735ec..bf11e2e 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ # Go workspace file go.work +result_test.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..cbb5134 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/inoth/result + +go 1.21 diff --git a/result.code-workspace b/result.code-workspace new file mode 100644 index 0000000..362d7c2 --- /dev/null +++ b/result.code-workspace @@ -0,0 +1,7 @@ +{ + "folders": [ + { + "path": "." + } + ] +} \ No newline at end of file diff --git a/result.go b/result.go new file mode 100644 index 0000000..1875759 --- /dev/null +++ b/result.go @@ -0,0 +1,56 @@ +package result + +type Result[T any] struct { + val T + err error +} + +func (r Result[T]) Ok() bool { + return r.err == nil +} + +func (r Result[T]) Err() error { + return r.err +} + +func (r Result[T]) Unwrap() T { + if r.err != nil { + panic(r.err) + } + return r.val +} + +func (r Result[T]) Expect(errs ...error) T { + if r.err != nil { + if len(errs) > 0 { + panic(errs[0]) + } + panic(r.err) + } + return r.val +} + +func (r Result[T]) Match(okFn func(val T), errFn func(err error)) { + if r.Ok() { + okFn(r.val) + } else { + errFn(r.err) + } +} + +func New[T any](val T, errs ...error) Result[T] { + res := Result[T]{ + val: val, + } + if len(errs) > 0 { + res.err = errs[0] + } + return res +} + +func Must[T any](val T, err error) Result[T] { + return Result[T]{ + val: val, + err: err, + } +}