result

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 1 Imported by: 0

README

go-result

CI Go Reference License

Generic Result type for Go — Ok[T] / Err[T] with mapping and chaining

Installation

go get github.com/philiprehberger/go-result

Usage

Basic Result
import "github.com/philiprehberger/go-result"

r := result.Ok(42)
fmt.Println(r.Unwrap()) // 42

r2 := result.Err[int](errors.New("not found"))
fmt.Println(r2.UnwrapOr(0)) // 0
UnwrapOrElse — Compute Default from Error
val := r.UnwrapOrElse(func(err error) int {
    log.Printf("falling back due to: %v", err)
    return -1
})
Expect — Unwrap with Custom Panic Message
cfg := r.Expect("config must be valid")
// panics with "config must be valid: <error>" if Err
Or — Fallback Result
r := result.Err[int](errors.New("fail"))
val := r.Or(result.Ok(42)) // Ok(42)
String Representation
fmt.Println(result.Ok(42))              // Ok(42)
fmt.Println(result.Err[int](err))       // Err(something failed)

Note: Unwrap() and Expect() panic if the Result is an error. Use UnwrapOr or UnwrapOrElse for safe extraction.

Try — Wrap (T, error)
r := result.Try(func() (int, error) {
    return strconv.Atoi("42")
})
// Ok(42)
Map and FlatMap
r := result.Ok(10)
doubled := result.Map(r, func(v int) int { return v * 2 })
// Ok(20)

chained := result.FlatMap(r, func(v int) result.Result[string] {
    return result.Ok(fmt.Sprintf("value: %d", v))
})
Match
msg := result.Match(r,
    func(v int) string { return fmt.Sprintf("got %d", v) },
    func(err error) string { return fmt.Sprintf("error: %v", err) },
)
Error Recovery
r := result.Err[int](errors.New("primary failed"))
val := r.OrElse(func(err error) result.Result[int] {
    log.Printf("recovering from: %v", err)
    return result.Ok(fallbackValue())
})
Filtering
r := result.Ok(age)
valid := r.Filter(
    func(v int) bool { return v >= 18 },
    func(v int) error { return fmt.Errorf("age %d is below minimum 18", v) },
)
Predicate Checks
r := result.Ok(42)
r.IsOkAnd(func(v int) bool { return v > 0 })   // true
r.IsErrAnd(func(err error) bool { return true }) // false
Side Effects
r := result.Ok(42)
r.Tap(func(v int) { log.Printf("got value: %d", v) }).
    TapErr(func(err error) { log.Printf("got error: %v", err) })
Collect Results
results := []result.Result[int]{result.Ok(1), result.Ok(2), result.Ok(3)}
combined := result.All(results) // Ok([1, 2, 3])

API

Function / Method Description
Result[T] Generic type representing either a success or error value
Ok[T](value T) Result[T] Create a successful Result
Err[T](err error) Result[T] Create a failed Result
Errf[T](format string, args ...any) Result[T] Create a failed Result with formatted error
Try[T](fn func() (T, error)) Result[T] Wrap a (T, error) call into a Result
Map[T, U](r Result[T], fn func(T) U) Result[U] Transform the success value
FlatMap[T, U](r Result[T], fn func(T) Result[U]) Result[U] Chain Results with a function returning Result
All[T](results []Result[T]) Result[[]T] Collect a slice of Results into a single Result
Match[T, U](r Result[T], onOk func(T) U, onErr func(error) U) U Pattern match on Ok or Err
(Result[T]) IsOk() bool True if the Result is a success
(Result[T]) IsErr() bool True if the Result is an error
(Result[T]) IsOkAnd(fn func(T) bool) bool True if Ok and value matches predicate
(Result[T]) IsErrAnd(fn func(error) bool) bool True if Err and error matches predicate
(Result[T]) Unwrap() T Return success value or panic
(Result[T]) Expect(msg string) T Return success value or panic with message
(Result[T]) UnwrapOr(def T) T Return success value or the provided default
(Result[T]) UnwrapOrElse(fn func(error) T) T Return success value or compute from error
(Result[T]) Or(other Result[T]) Result[T] Return self if Ok, otherwise the fallback
(Result[T]) OrElse(fn func(error) Result[T]) Result[T] Return self if Ok, otherwise compute fallback
(Result[T]) Filter(pred func(T) bool, errFn func(T) error) Result[T] Convert to Err if value fails predicate
(Result[T]) Tap(fn func(T)) Result[T] Run side effect on Ok value, return unchanged
(Result[T]) TapErr(fn func(error)) Result[T] Run side effect on Err value, return unchanged
(Result[T]) Error() error Return the error or nil
(Result[T]) String() string Human-readable representation

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package result provides a generic Result type for Go inspired by Rust's Result<T, E>.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Match

func Match[T any, U any](r Result[T], onOk func(T) U, onErr func(error) U) U

Match applies one of two functions depending on whether the Result is Ok or Err.

Types

type Result

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

Result represents either a success value (Ok) or an error value (Err).

func All

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

All collects a slice of Results into a Result containing a slice of values. Returns the first error encountered.

func Err

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

Err creates a failed Result containing the given error.

func Errf

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

Errf creates a failed Result with a formatted error message.

func FlatMap

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

FlatMap transforms the success value using a function that returns a Result.

func Map

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

Map transforms the success value using the given function.

func Ok

func Ok[T any](value T) Result[T]

Ok creates a successful Result containing the given value.

func Try

func Try[T any](fn func() (T, error)) Result[T]

Try wraps a function call that returns (T, error) into a Result.

func (Result[T]) Error

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

Error returns the error value or nil if the Result is Ok.

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

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

Expect returns the success value or panics with the given message if the Result is an error.

func (Result[T]) Filter added in v0.4.0

func (r Result[T]) Filter(predicate func(T) bool, errFn func(T) error) Result[T]

Filter returns Err if the Ok value doesn't match the predicate. errFn produces the error from the value.

func (Result[T]) IsErr

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

IsErr returns true if the Result is an error.

func (Result[T]) IsErrAnd added in v0.4.0

func (r Result[T]) IsErrAnd(predicate func(error) bool) bool

IsErrAnd returns true if the Result is Err and the error matches the predicate.

func (Result[T]) IsOk

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

IsOk returns true if the Result is a success.

func (Result[T]) IsOkAnd added in v0.4.0

func (r Result[T]) IsOkAnd(predicate func(T) bool) bool

IsOkAnd returns true if the Result is Ok and the value matches the predicate.

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

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

Or returns the Result if it is Ok, otherwise returns the provided fallback Result.

func (Result[T]) OrElse added in v0.4.0

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

OrElse returns r if Ok, otherwise calls fn with the error to produce an alternative Result.

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

func (r Result[T]) String() string

String returns a human-readable representation of the Result.

func (Result[T]) Tap added in v0.4.0

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

Tap calls fn with the Ok value for side effects, then returns the original Result unchanged.

func (Result[T]) TapErr added in v0.4.0

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

TapErr calls fn with the error for side effects, then returns the original Result unchanged.

func (Result[T]) Unwrap

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

Unwrap returns the success value or panics if the Result is an error.

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(def T) T

UnwrapOr returns the success value or the provided default.

func (Result[T]) UnwrapOrElse

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

UnwrapOrElse returns the success value or calls the provided function.

Jump to

Keyboard shortcuts

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