Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
inoth committed Feb 23, 2024
1 parent f641a6d commit 95301b8
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@

# Go workspace file
go.work
result_test.go
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/inoth/result

go 1.21
7 changes: 7 additions & 0 deletions result.code-workspace
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"folders": [
{
"path": "."
}
]
}
56 changes: 56 additions & 0 deletions result.go
Original file line number Diff line number Diff line change
@@ -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,
}
}

0 comments on commit 95301b8

Please sign in to comment.