Overview
Result provides several methods for transforming values:map()- Transform success valuesmapError()- Transform error valuesandThen()- Chain operations that return Resultstap()- Run side effects without changing the Result
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:
Transforming Error Values
Result.mapError()
Transforms the error value while preserving success.Normalizing Error Types
UsemapError() 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
- Use map
- Use andThen
When the transformation cannot fail:
Error Type Union
andThen() automatically unions error types from all steps:
Type Signature
Result.andThenAsync()
Async version ofandThen() 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
Result.tapAsync()
Async version oftap() for async side effects:
Type Signature
Extracting Values
Result.unwrap()
Extracts the success value or throws aPanic if the Result is an error.
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
map() - Transform success values
map() - Transform success values
Use when transformation cannot fail. Errors pass through unchanged.
mapError() - Transform error values
mapError() - Transform error values
Use to normalize error types or add context. Success values pass through.
andThen() - Chain failing operations
andThen() - Chain failing operations
Use when transformation can fail and returns a Result. Errors short-circuit.
tap() - Run side effects
tap() - Run side effects
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