Skip to main content

Overview

Result provides several methods for transforming values:
  • map() - Transform success values
  • mapError() - Transform error values
  • andThen() - Chain operations that return Results
  • tap() - Run side effects without changing the Result
All methods support both data-first (method-style) and data-last (pipeable) APIs.

Transforming Success Values

Result.map()

Transforms the success value while preserving errors.

Type Signature

Data-First (Method Style)

Data-Last (Pipeable Style)

The pipeable API is useful for building reusable transformation pipelines without nesting.

Error Handling in map()

If the transformation function throws, map() will throw a Panic:
Never throw inside map(). If your transformation can fail, use andThen() instead and return a Result.

Transforming Error Values

Result.mapError()

Transforms the error value while preserving success.

Normalizing Error Types

Use mapError() to convert error unions to a single error type:

Type Signature

Chaining Operations

Result.andThen()

Chains a function that returns a Result, enabling sequential composition where each step can fail.

map vs andThen

When the transformation cannot fail:

Error Type Union

andThen() automatically unions error types from all steps:

Type Signature

Result.andThenAsync()

Async version of andThen() for chaining async operations:

Type Signature

Side Effects

Result.tap()

Runs a side effect on success values without changing the Result. Useful for logging, metrics, or debugging.

Practical Example

If the tap callback throws, it will throw a Panic. Keep side effects simple and don’t throw.

Result.tapAsync()

Async version of tap() for async side effects:

Type Signature

Extracting Values

Result.unwrap()

Extracts the success value or throws a Panic if the Result is an error.
Only use unwrap() when you’re certain the Result is Ok (e.g., after type narrowing with isOk()), or when a panic is acceptable.

Result.unwrapOr()

Extracts the success value or returns a fallback if the Result is an error.

Type Widening

The return type is the union of success type and fallback type:

Real-World Example

Here’s a complete example combining multiple transformations:

Summary

Use when transformation cannot fail. Errors pass through unchanged.
Use to normalize error types or add context. Success values pass through.
Use when transformation can fail and returns a Result. Errors short-circuit.
Use for logging, metrics, or debugging. Returns original Result unchanged.

Next Steps

Pattern Matching

Learn how to handle both success and error cases with match()

Generator Composition

Master Result.gen() for imperative-style error handling