Documentation
¶
Overview ¶
Package rslt models success-or-error outcomes as values.
Result holds either an Ok value or an Err error. Unlike bare (T, error) pairs, a Result is a single value that chains through Result.Transform, Result.FlatMap, and standalone Map — errors propagate automatically without if-err checks at each step.
Construct via Ok, Err, or Of. The zero value is Ok containing R's zero value, which silently reports success. Always construct explicitly.
Extract via Result.Get, Result.Or, Result.Unpack, or Result.MustGet (panics on Err). Convert between Result and (T, error) with Of and Result.Unpack.
For [option.Option] interop, see Result.Get (returns value + bool) and Fold (eliminates both branches).
Example ¶
package main
import (
"fmt"
"strconv"
"github.com/binaryphile/fluentfp/rslt"
)
func main() {
// Parse a string to int, double it, format back to string.
// Errors propagate automatically — no if-err checks.
result := rslt.Of(strconv.Atoi("21")).
Transform(func(n int) int { return n * 2 })
fmt.Println(result.Or(0))
}
Output: 42
Example (ErrorPropagation) ¶
package main
import (
"fmt"
"strconv"
"github.com/binaryphile/fluentfp/rslt"
)
func main() {
// When the first step fails, Transform is skipped.
result := rslt.Of(strconv.Atoi("not a number")).
Transform(func(n int) int { return n * 2 })
fmt.Println("ok:", result.IsOk())
}
Output: ok: false
Index ¶
- func CollectAll[R any](results []Result[R]) ([]R, error)
- func CollectErr[R any](results []Result[R]) []error
- func CollectOk[R any](results []Result[R]) []R
- func CollectOkAndErr[R any](results []Result[R]) ([]R, []error)
- func Fold[R, T any](res Result[R], onErr func(error) T, onOk func(R) T) T
- func Lift[A, R any](fn func(A) (R, error)) func(A) Result[R]
- func LiftCtx[T, R any](ctx context.Context, fn func(context.Context, T) (R, error)) func(T) Result[R]
- type AsyncResult
- type PanicError
- type Result
- func (r Result[R]) Err() error
- func (r Result[R]) FlatMap(fn func(R) Result[R]) Result[R]
- func (r Result[R]) Get() (_ R, _ bool)
- func (r Result[R]) GetErr() (_ error, _ bool)
- func (r Result[R]) IfErr(fn func(error))
- func (r Result[R]) IfOk(fn func(R))
- func (r Result[R]) IsErr() bool
- func (r Result[R]) IsOk() bool
- func (r Result[R]) MapErr(fn func(error) error) Result[R]
- func (r Result[R]) MustGet() R
- func (r Result[R]) Or(defaultVal R) R
- func (r Result[R]) OrCall(fn func() R) R
- func (r Result[R]) Tap(fn func(R)) Result[R]
- func (r Result[R]) TapErr(fn func(error)) Result[R]
- func (r Result[R]) Transform(fn func(R) R) Result[R]
- func (r Result[R]) Unpack() (R, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CollectAll ¶
CollectAll returns all values if every result is Ok, or the first error by index order otherwise. Note: for concurrent results from [FanOut], index order may differ from completion order.
func CollectErr ¶
CollectErr returns the errors from all Err results, preserving order.
func CollectOkAndErr ¶
CollectOkAndErr splits results into Ok values and Err errors in a single pass, preserving order.
func LiftCtx ¶ added in v0.53.0
func LiftCtx[T, R any](ctx context.Context, fn func(context.Context, T) (R, error)) func(T) Result[R]
LiftCtx wraps a context-aware fallible function, partially applying the context. The returned function takes only the value argument and returns Result — suitable for use with FlatMap in a chain.
Types ¶
type AsyncResult ¶ added in v0.57.0
type AsyncResult[R any] struct { // contains filtered or unexported fields }
AsyncResult holds the outcome of a background goroutine launched by RunAsync. Use AsyncResult.Wait to block for the result or AsyncResult.Done to compose with select.
AsyncResult is safe to copy -- copies share the same underlying state. The zero value is not valid; use RunAsync to create. Methods panic with a descriptive message on zero-value handles.
AsyncResult is intentionally non-comparable to avoid accidental use as a map key or in equality checks.
func RunAsync ¶ added in v0.57.0
RunAsync launches fn in a goroutine and returns a handle to wait on the result. Panics in fn are recovered and wrapped as *PanicError with a stack trace -- an unrecovered panic in a background goroutine would crash the entire process.
Only panics on fn's goroutine are recovered. If fn launches additional goroutines, panics in those are not caught.
The caller owns ctx and is responsible for cancellation. RunAsync does not add its own cancel or timeout.
Panics if fn or ctx is nil.
func (AsyncResult[R]) Done ¶ added in v0.57.0
func (a AsyncResult[R]) Done() <-chan struct{}
Done returns a channel that closes when the goroutine completes. Closes exactly once. Composable with select:
select {
case <-result.Done():
val, err := result.Wait()
case <-ctx.Done():
// timed out waiting
}
func (AsyncResult[R]) String ¶ added in v0.57.0
func (a AsyncResult[R]) String() string
String returns a human-readable description of the async result's state (pending, ok, or error).
func (AsyncResult[R]) Wait ¶ added in v0.57.0
func (a AsyncResult[R]) Wait() (R, error)
Wait blocks until the goroutine completes and returns the result. Safe to call from multiple goroutines and multiple times -- always returns the same value. May block forever if fn never returns.
type PanicError ¶
PanicError wraps a recovered panic value and its stack trace. It is stored as *PanicError in Err results. Callers detect it via errors.As(err, &pe) where pe is *PanicError.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
Error returns a string representation of the panic value.
func (*PanicError) Unwrap ¶
func (e *PanicError) Unwrap() error
Unwrap returns the panic value if it is an error, or nil otherwise. This preserves error chains: errors.Is(resultErr, context.Canceled) works when fn panics with a wrapped context error.
type Result ¶
type Result[R any] struct { // contains filtered or unexported fields }
Result represents the outcome of an operation that may fail. It holds either a value (Ok) or an error (Err).
The zero value is Ok containing R's zero value. This means an uninitialized Result (e.g. a struct field never assigned) silently reports success. Always construct results explicitly via Ok, Err, or Of.
func FlatMap ¶
FlatMap applies fn to the value if res is Ok, returning fn's Result. Returns Err unchanged. fn is called at most once and is not retained. Panics if fn is nil and res is Ok.
func Map ¶
Map applies fn to the value if res is Ok, returning a new Ok. Returns Err unchanged. fn is called at most once and is not retained. Panics if fn is nil and res is Ok.
func Of ¶
Of returns a Result from a (value, error) pair — the signature returned by most Go functions. If err is non-nil the result is Err; otherwise Ok.
func (Result[R]) FlatMap ¶
FlatMap applies fn to the value if r is Ok. Returns r unchanged if Err. fn is called at most once and is not retained. Panics if fn is nil and r is Ok.
func (Result[R]) Get ¶
Get returns the value and true if r is Ok, or the zero value and false if r is Err.
func (Result[R]) GetErr ¶
GetErr returns the error and true if r is Err, or nil and false if r is Ok.
func (Result[R]) IfOk ¶
func (r Result[R]) IfOk(fn func(R))
IfOk calls fn with the value if r is Ok.
func (Result[R]) MapErr ¶
MapErr returns a Result with the error transformed by fn if r is Err, or r unchanged if r is Ok. Useful for wrapping or annotating errors without losing the Result context. Panics if fn returns nil (same as Err).
func (Result[R]) MustGet ¶
func (r Result[R]) MustGet() R
MustGet returns the value if r is Ok, or panics with the error if r is Err. The panic value wraps the original error, preserving error chains for errors.Is and errors.As after recovery.
func (Result[R]) Or ¶
func (r Result[R]) Or(defaultVal R) R
Or returns the value if r is Ok, or defaultVal if r is Err.
func (Result[R]) OrCall ¶
func (r Result[R]) OrCall(fn func() R) R
OrCall returns the value if r is Ok, or the result of calling fn if r is Err. fn is called at most once and only when r is Err.
func (Result[R]) Tap ¶ added in v0.49.0
Tap calls fn with the value if r is Ok and returns r unchanged. Use for side effects (logging, storage) that should not alter the Result.
func (Result[R]) TapErr ¶ added in v0.50.0
TapErr calls fn with the error if r is Err and returns r unchanged. Use for error-side side effects (logging, metrics) that should not alter the Result.