result

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package result provides a generic Result[T] type that represents either a success value or an error.

Map, FlatMap, and Then use Go 1.27 generic methods, enabling clean method-chaining across type boundaries without nested free functions.

user, err := result.From(verifier.Verify(ctx, token)).
    MapErr(wrapUnauthorized).
    Then(upsertUser).
    FlatMap(ensurePlan).
    Then(buildDTO).
    Unwrap()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains added in v0.9.0

func Contains[T comparable](r Result[T], target T) bool

Contains reports whether r holds a success value equal to target.

func Failures added in v0.2.0

func Failures[T any](results []Result[T]) []error

Failures returns every error, dropping success values — Haskell's lefts.

func Successes added in v0.2.0

func Successes[T any](results []Result[T]) []T

Successes returns every success value, dropping errors — Haskell's rights. Unlike Sequence, this never fails: a Result slice with no successes returns an empty slice.

Types

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result holds either a success value of type T or an error. The two are mutually exclusive by construction (Err refuses a nil error, OK never sets one), so err's nilness alone is the discriminant — there's no separate tag to keep in sync. Use OK, Err, or From to construct; never use the zero value directly.

func Err

func Err[T any](err error) Result[T]

Err wraps a failure. Panics if err is nil — use OK for success.

func Flatten added in v0.9.0

func Flatten[T any](r Result[Result[T]]) Result[T]

Flatten collapses a nested Result[Result[T]] into a single Result[T].

func From

func From[T any](val T, err error) Result[T]

From converts a Go-idiomatic (val, error) pair.

func FromNonZero added in v0.11.0

func FromNonZero[T comparable](val T, err error) Result[T]

FromNonZero returns OK(val) if val is non-zero (val != zero); otherwise it returns Err[T](err).

func OK

func OK[T any](val T) Result[T]

OK wraps a success value.

func Sequence added in v0.2.0

func Sequence[T any](results []Result[T]) Result[[]T]

Sequence turns a slice of Results into a Result of a slice, fail-fast on the first error encountered — Haskell's sequence/traverse for []Result.

func Void added in v0.14.0

func Void() Result[unit.Unit]

Void returns a successful Result carrying no value.

func Zip2 added in v0.2.0

func Zip2[A, B, U any](ra Result[A], rb Result[B], fn func(A, B) U) Result[U]

Zip2 combines two independent Results into one via fn. Both must succeed; the first failure (ra, then rb) short-circuits.

func Zip3 added in v0.2.0

func Zip3[A, B, C, U any](ra Result[A], rb Result[B], rc Result[C], fn func(A, B, C) U) Result[U]

Zip3 combines three independent Results into one via fn. All three must succeed; the first failure (ra, then rb, then rc) short-circuits.

func (Result[T]) Expect added in v0.2.0

func (r Result[T]) Expect(msg string) T

Expect returns the success value or panics with msg wrapping the underlying error — the friendly alternative to MustGet for init/construction code, where a bare stack trace on the raw error isn't enough context to diagnose from. Prefer this over chaining MapErr(wrapErr(msg)).MustGet() for the same effect.

func (Result[T]) FlatMap

func (r Result[T]) FlatMap[U any](fn func(T) Result[U]) Result[U]

FlatMap chains a Result-returning operation. Errors short-circuit: a failed Result never calls fn.

func (Result[T]) Fold added in v0.2.0

func (r Result[T]) Fold[U any](onOK func(T) U, onErr func(error) U) U

Fold collapses the Result into a single value of type U by handling both branches — onOK for success, onErr for failure. Equivalent to Haskell's either or Rust's map_or_else, and shorter than the equivalent Map(onOK).OrElseGet(onErr) two-step.

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr reports whether the Result holds an error.

func (Result[T]) IsOK

func (r Result[T]) IsOK() bool

IsOK reports whether the Result holds a success value.

func (Result[T]) Map

func (r Result[T]) Map[U any](fn func(T) U) Result[U]

Map transforms the success value into a different type. Errors propagate unchanged.

func (Result[T]) Map0 added in v0.14.0

func (r Result[T]) Map0[U any](fn func() U) Result[U]

Map0 maps the Result to a new type by calling fn with no arguments, ignoring the current value. Errors propagate unchanged.

func (Result[T]) MapErr

func (r Result[T]) MapErr(fn func(error) error) Result[T]

MapErr transforms the error, leaving a success Result unchanged. Use to annotate errors with context before they surface to callers.

func (Result[T]) MapErrf added in v0.9.0

func (r Result[T]) MapErrf(format string, args ...any) Result[T]

MapErrf annotates an error with a formatted context string if Result holds an error. If format does not contain %w, ": %w" is automatically appended along with the underlying error, preserving the error wrapping chain for errors.Is/errors.As.

func (Result[T]) MarshalJSON added in v0.3.0

func (r Result[T]) MarshalJSON() ([]byte, error)

MarshalJSON writes the Result as {"ok":<val>} or {"err":"<message>"}.

func (Result[T]) MustErr added in v0.12.0

func (r Result[T]) MustErr() error

MustErr returns the error or panics if the Result is OK. Intended for tests and template rendering where error presence is guarded by IsErr().

func (Result[T]) MustGet

func (r Result[T]) MustGet() T

MustGet returns the success value or panics with the error. Intended for tests and initialisation code only.

func (Result[T]) Or added in v0.9.0

func (r Result[T]) Or(fallback Result[T]) Result[T]

Or returns r if it holds a success value; otherwise it returns fallback Result.

func (Result[T]) OrElse

func (r Result[T]) OrElse(fallback T) T

OrElse returns the success value, or fallback on failure. fallback is evaluated by the caller before this is called, regardless of branch — Go has no way to defer argument evaluation — the same gotcha as Rust's unwrap_or and Java's Optional.orElse. Use OrElseGet if fallback is expensive to compute.

func (Result[T]) OrElseGet

func (r Result[T]) OrElseGet(fn func(error) T) T

OrElseGet calls fn with the error to produce a fallback value on failure.

func (Result[T]) Recover added in v0.2.0

func (r Result[T]) Recover(fn func(error) Result[T]) Result[T]

Recover turns a failure into a fallback Result via fn — the fallback may itself fail. A success Result passes through unchanged. Use for retry paths or default-value fallbacks that are themselves fallible; for a fallback that can't fail, use OrElse/OrElseGet instead.

func (Result[T]) Tap

func (r Result[T]) Tap(fn func(T)) Result[T]

Tap calls fn on the success value for side effects (e.g. metrics, tracing) and passes the Result through unchanged.

func (Result[T]) TapErr

func (r Result[T]) TapErr(fn func(error)) Result[T]

TapErr calls fn on the error for side effects (e.g. logging) and passes the Result through unchanged.

func (Result[T]) Then

func (r Result[T]) Then[U any](fn func(T) (U, error)) Result[U]

Then chains a Go-idiomatic (U, error)-returning function.

func (*Result[T]) UnmarshalJSON added in v0.3.0

func (r *Result[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON reads back the shape MarshalJSON writes. The reconstructed error is a plain errors.New(message) — the original error's identity and wrapping chain don't survive the round-trip, only its message text.

This can't reuse wireResult the way MarshalJSON does: encoding/json collapses a JSON null into a nil pointer at whatever level it's unmarshaling into, so a *T field can't tell "ok present, value null" (a real success holding a nil T, e.g. Result[*Invoice]'s "no match") apart from "ok absent". Unmarshaling into a raw key map first, and checking key presence directly, avoids that collapse.

func (Result[T]) Unwrap

func (r Result[T]) Unwrap() (T, error)

Unwrap returns the underlying (value, error) pair, matching Go's standard multi-return convention for direct use in callers.

func (Result[T]) WrapErr added in v0.9.0

func (r Result[T]) WrapErr(format string, args ...any) Result[T]

WrapErr is an alias for MapErrf.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL