File tree Expand file tree Collapse file tree 3 files changed +63
-1
lines changed Expand file tree Collapse file tree 3 files changed +63
-1
lines changed Original file line number Diff line number Diff line change 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 {}]{}
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 11package 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
You can’t perform that action at this time.
0 commit comments