Skip to content

Commit 41d17e1

Browse files
authored
Support unmarshaling values into result.Ok variants
1 parent 83c7a18 commit 41d17e1

File tree

3 files changed

+63
-1
lines changed

3 files changed

+63
-1
lines changed

result/json.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package result
2+
3+
import "encoding/json"
4+
5+
// UnmarshalJSON implements the [json.Unmarshaler] interface.
6+
// Values will be unmarshaled as [Ok] variants.
7+
func (r *Result[T]) UnmarshalJSON(data []byte) error {
8+
var value T
9+
10+
if err := json.Unmarshal(data, &value); err != nil {
11+
return err
12+
}
13+
14+
*r = Ok(value)
15+
return nil
16+
}
17+
18+
var _ json.Unmarshaler = &Result[struct{}]{}

result/json_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package result_test
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"github.com/BooleanCat/go-functional/internal/assert"
7+
"github.com/BooleanCat/go-functional/result"
8+
"testing"
9+
)
10+
11+
func ExampleResult_UnmarshalJSON() {
12+
var r result.Result[[]string]
13+
14+
_ = json.Unmarshal([]byte(`["Foo", "Bar"]`), &r)
15+
16+
value, _ := r.Value()
17+
18+
fmt.Println(value)
19+
20+
// Output:
21+
// [Foo Bar]
22+
}
23+
24+
func TestUnmarshalJSON(t *testing.T) {
25+
var r result.Result[[]string]
26+
27+
err := json.Unmarshal([]byte(`["Foo", "Bar"]`), &r)
28+
assert.Nil(t, err)
29+
30+
value, err := r.Value()
31+
assert.Nil(t, err)
32+
33+
assert.SliceEqual(t, value, []string{"Foo", "Bar"})
34+
}
35+
36+
func TestUnmarshalError(t *testing.T) {
37+
var r result.Result[string]
38+
39+
err := json.Unmarshal([]byte("42"), &r)
40+
41+
assert.NotNil(t, err)
42+
}

result/result.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package result
22

3-
import "fmt"
3+
import (
4+
"fmt"
5+
)
46

57
// Result represents failure or success. The [Ok] variant represents success
68
// and contains a value. The [Err] variant represent a failure and contains an

0 commit comments

Comments
 (0)