Skip to content

Commit

Permalink
feat: improve async.Result ergonomics
Browse files Browse the repository at this point in the history
  • Loading branch information
brianmcgee committed Sep 27, 2022
1 parent dbf29cc commit 5fc8aa5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
10 changes: 8 additions & 2 deletions result.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@ func (r result[T]) Unwrap() (T, error) {
return r.value, r.err
}

// NewResult creates a successful result.
func NewResult[T any](value T) Result[T] {
// NewResult creates a result instance with a provided value and error. It's sometimes more convenient to instantiate
// like this when implementing library code.
func NewResult[T any](value T, err error) Result[T] {
return result[T]{value: value, err: err}
}

// NewResultValue creates a successful result.
func NewResultValue[T any](value T) Result[T] {
return result[T]{value: value}
}

Expand Down
17 changes: 15 additions & 2 deletions result_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

func ExampleNewResult() {
result := NewResult[string]("success")
result := NewResultValue[string]("success")
v, _ := result.Unwrap()
println(v)
}
Expand All @@ -20,7 +20,20 @@ func ExampleNewResultErr() {
}

func TestNewResult(t *testing.T) {
r := NewResult[string]("hello")
r := NewResult[string]("hello", nil)
value, err := r.Unwrap()
assert.Equal(t, "hello", value)
assert.Nil(t, err)

expected := errors.New("something bad happened")
r = NewResult[string]("", expected)
value, err = r.Unwrap()
assert.Equal(t, "", value)
assert.Equal(t, expected, err)
}

func TestNewResultValue(t *testing.T) {
r := NewResultValue[string]("hello")
value, err := r.Unwrap()
assert.Equal(t, "hello", value)
assert.Nil(t, err)
Expand Down

0 comments on commit 5fc8aa5

Please sign in to comment.