-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
93 lines (76 loc) · 1.41 KB
/
result.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package types
import "encoding/json"
type Result[T any] struct {
value T
err error
}
func Ok[T any](a T) Result[T] {
return Result[T]{value: a}
}
func Err[T any](a error) Result[T] {
return Result[T]{err: a}
}
func (a Result[T]) Val() (value T, err error) {
return a.value, a.err
}
func (a Result[T]) OrPanic() T {
if a.err != nil {
panic("error of result")
}
return a.value
}
func (a Result[T]) Or(value T) T {
if a.err != nil {
return value
}
return a.value
}
func (a Result[T]) OrDefault() (v T) {
if a.err != nil {
return
}
return a.value
}
func (a Result[T]) IsOk() bool {
return a.err == nil
}
func (a Result[T]) IsOkAnd(f func(T) bool) bool {
if a.err != nil {
return false
}
return f(a.value)
}
func (a Result[T]) IsErr() bool {
return a.err != nil
}
func (a Result[T]) IsErrAnd(f func(error) bool) bool {
if a.err == nil {
return false
}
return f(a.err)
}
func (a Result[T]) IfOk(action func(value T)) {
if a.err == nil {
action(a.value)
}
}
func (a Result[T]) IfErr(action func(err error)) {
if a.err != nil {
action(a.err)
}
}
func (a *Result[T]) MarshalJSON() ([]byte, error) {
if a.err == nil {
return json.Marshal(a.value)
}
return []byte("null"), a.err
}
func (a *Result[T]) UnmarshalJSON(data []byte) error {
if len(data) < 5 && string(data) == "null" {
return nil
}
return json.Unmarshal(data, &a.value)
}
func ResultVal[T any](v T, err error) T {
return v
}