Skip to content

Commit

Permalink
add result package
Browse files Browse the repository at this point in the history
  • Loading branch information
A-yon Lee committed Jan 1, 2025
1 parent 76359cb commit a81b61e
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
46 changes: 46 additions & 0 deletions result/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package result_test

import (
"fmt"
"strconv"

"github.com/ayonli/goext/result"
)

func ExampleWrap() {
mathAdd := func(input1 string, input2 string) (int, error) {
return result.Wrap(func() (int, error) {
num1 := result.Unwrap(strconv.Atoi(input1))
num2 := result.Unwrap(strconv.Atoi(input2))
return num1 + num2, nil
})
}

res, err := mathAdd("10", "20")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
}
// Output:
// 30
}

func ExampleUnwrap() {
mathAdd := func(input1 string, input2 string) (int, error) {
return result.Wrap(func() (int, error) {
num1 := result.Unwrap(strconv.Atoi(input1))
num2 := result.Unwrap(strconv.Atoi(input2))
return num1 + num2, nil
})
}

res, err := mathAdd("10", "20")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
}
// Output:
// 30
}
30 changes: 30 additions & 0 deletions result/result.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package result

import (
"errors"
"fmt"
)

func Wrap[R any](fn func() (value R, err error)) (value R, err error) {
defer func() {
if re := recover(); re != nil {
if _err, ok := re.(error); ok {
err = _err
} else if str, ok := re.(string); ok {
err = errors.New(str)
} else {
err = errors.New(fmt.Sprint(re))
}
}
}()

return fn()
}

func Unwrap[R any](value R, err error) R {
if err != nil {
panic(err)
}

return value
}

0 comments on commit a81b61e

Please sign in to comment.