-
Notifications
You must be signed in to change notification settings - Fork 0
/
maybe.go
72 lines (58 loc) · 1.31 KB
/
maybe.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
package errors
// Maybe panics if err is not nil and doesn't implement T.
// Returns T if err is of type T.
//
// Useful for panic unless error can be handled.
func Maybe[E error](err error) (t E) {
if err == nil {
return
}
if Is(err, t) {
return err.(E)
}
mayPanicf(err, "")
return
}
// Maybef is same as Maybe, but returns a formatter function which panics with the given formatted error message.
func Maybef[E error](err error) func(format string, params ...any) E {
return func(format string, params ...any) (t E) {
if err == nil {
return
}
if Is(err, t) {
return err.(E)
}
mayPanicf(err, format, params...)
return
}
}
// MaybeResult is same as Maybe, but it's used for returning a result.
func MaybeResult[T any, E error](r T, err error) (t T, e E) {
t = r
if err == nil {
t = r
return
}
if Is(err, e) {
e = err.(E)
return
}
mayPanicf(err, "")
return
}
// MaybeResultf is same as MaybeResult, but returns a formatter function which panics with the given formatted error message.
func MaybeResultf[T any, E error](r T, err error) func(format string, params ...any) (t T, e E) {
return func(format string, params ...any) (t T, e E) {
t = r
if err == nil {
t = r
return
}
if Is(err, e) {
e = err.(E)
return
}
mayPanicf(err, format, params...)
return
}
}