-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
67 lines (55 loc) · 1.17 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
// SPDX-License-Identifier: 0BSD
package sx
import "errors"
func NewResultFrom[V any](value V) Result[V] {
var opt = Result[V]{data: value, err: nil}
return opt
}
func NewResultError[V any](errorMessageParts ...string) Result[V] {
var opt = Result[V]{err: errors.New(StrCat(errorMessageParts...))}
return opt
}
func NewResultFromError[V any](err error) Result[V] {
var opt = Result[V]{err: err}
return opt
}
type Result[T any] struct {
data T
err error
}
func (r Result[T]) Ok() bool {
return r.err == nil
}
func (r Result[T]) Value() T {
if !r.Ok() {
Throw(r.err.Error())
}
return r.data
}
func (r Result[T]) ValueOrThrow(errorMessage string) T {
if !r.Ok() {
ThrowIfError(errors.New(errorMessage))
}
return r.data
}
func (r Result[T]) ValueOr(defaultValue T) T {
if !r.Ok() {
return defaultValue
}
return r.data
}
func (r Result[T]) ValueOrInit() (value T) {
return r.ValueOr(value)
}
func (r Result[T]) ValueIsOptional() Optional[T] {
if !r.Ok() {
return NewOptional[T]()
}
return NewOptionalFrom(r.Value())
}
func (r Result[T]) Error() string {
if r.Ok() {
Throw("Fatal error: accessing empty error value from result")
}
return r.err.Error()
}