forked from digisan/go-generics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
50 lines (43 loc) · 834 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
package gogenerics
import (
"errors"
"fmt"
)
type Result[T any] struct {
value T
err error
}
func (r *Result[T]) Unwrap() T {
if r.err == nil {
return r.value
}
panic(r.err.Error())
}
func (r *Result[T]) Expect(failMsg string) T {
if r.err == nil {
return r.value
}
err := fmt.Errorf("%s: %w", failMsg, r.err)
if len(failMsg) != 0 {
panic(err.Error())
}
panic(errors.Unwrap(err).Error())
}
func (r *Result[T]) SafeValue(err *error) (bool, T) {
defer func() {
if err == nil {
panic("'err' cannot be nil for holding error")
}
*err = r.err
}()
return r.err == nil, r.value
}
func NewResult[T any](value T, err error) Result[T] {
return Result[T]{
value: value,
err: err,
}
}
func NewFailResult[T any](value T, failMsg string) Result[T] {
return NewResult[T](value, errors.New(failMsg))
}