-
Notifications
You must be signed in to change notification settings - Fork 2
/
result.go
60 lines (49 loc) · 872 Bytes
/
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
package safetypes
import "errors"
type Result[T any] struct {
err error
value *T
}
func Ok[T any](value T) Result[T] {
return Result[T]{
value: &value,
err: nil,
}
}
func Err[T any](err string) Result[T] {
return Result[T]{
value: nil,
err: errors.New(err),
}
}
func AsResult[T any](value T, err error) Result[T] {
if err != nil {
return Err[T](err.Error())
}
return Ok(value)
}
func (r Result[T]) Ok(value T) Result[T] {
r.value = &value
r.err = nil
return r
}
func (r Result[T]) Err(err string) Result[T] {
r.value = nil
r.err = errors.New(err)
return r
}
func (r *Result[T]) IsOk() bool {
return r.err == nil
}
func (r *Result[T]) IsErr() bool {
return r.err != nil
}
func (r *Result[T]) Error() error {
return r.err
}
func (o *Result[T]) Unwrap() T {
if o.IsErr() {
panic("can't unwrap err value")
}
return *o.value
}