-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresult.go
73 lines (66 loc) · 1.28 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
package goption
// Result is interface to be the type of function return
type Result interface {
Ok(func(interface{})) Result
Err(func(error)) Result
Is_Ok() bool
Unwrap() interface{}
And_then(func(interface{}) (interface{}, error)) Result
}
type vOk struct {
v interface{}
}
//Ok returns the type vOk
func Ok(v interface{}) Result {
return &vOk{v: v}
}
func (v *vOk) Ok(f func(interface{})) Result {
f(v.v)
return v
}
func (v *vOk) Err(f func(error)) Result {
return v
}
func (v *vOk) Is_Ok() bool {
return true
}
func (v *vOk) Unwrap() interface{} {
return v.v
}
func (v *vOk) And_then(f func(interface{}) (interface{}, error)) Result {
tmp, err := f(v.v)
if err != nil {
return Err(err)
}
return &vOk{v: tmp}
}
type vErr struct {
v error
}
//Err returns the type vErr
func Err(v error) Result {
return &vErr{v: v}
}
func (v *vErr) Ok(f func(interface{})) Result {
return v
}
func (v *vErr) Err(f func(error)) Result {
f(v.v)
return v
}
func (v *vErr) Is_Ok() bool {
return false
}
func (v *vErr) Unwrap() interface{} {
panic(v.v)
}
func (v *vErr) And_then(f func(interface{}) (interface{}, error)) Result {
return v
}
//ToResult conver golang function return to result
func ToResult(i interface{}, err error) Result {
if err != nil {
return Err(err)
}
return Ok(i)
}