Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Result map, map_err and and_then

Reference for Rust Result::map, map_err, and_then, or_else, map_or and inspect: transform success and error values and chain fallible steps.

The combinator methods on Result let you transform a value or an error without writing a match. map changes the Ok value and leaves an Err alone; map_err does the opposite. and_then chains a second operation that is itself fallible, so the result stays a flat Result instead of becoming a nested one.

Chains of these methods read as a pipeline: parse, validate, convert. For longer functions the ? operator is often clearer, but combinators shine in short expressions and closures.

Rust
let n = "21".parse::<i32>().map(|v| v * 2);          // Ok(42)
let r = "x".parse::<i32>().map_err(|e| e.to_string()); // Err("invalid digit found in string")

Try it

Rust map, map_err and and_then

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Predicates, inspection and and/or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<T, E> Result<T, E> {
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E>;
    pub fn map_err<F2, O: FnOnce(E) -> F2>(self, op: O) -> Result<T, F2>;
    pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U;
    pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U;
    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E>;
    pub fn or_else<F2, O: FnOnce(E) -> Result<T, F2>>(self, op: O) -> Result<T, F2>;
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>;
    pub fn or<F2>(self, res: Result<T, F2>) -> Result<T, F2>;
    pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self;
    pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self;
}
Method Ok(v) becomes Err(e) becomes
map(f) Ok(f(v)) unchanged
map_err(f) unchanged Err(f(e))
and_then(f) f(v) unchanged
or_else(f) unchanged f(e)
and(r) r unchanged
or(r) unchanged r
map_or(d, f) f(v) d
map_or_else(g, f) f(v) g(e)

inspect and inspect_err (Rust 1.76) run a closure with a reference and return the result unchanged. is_ok_and and is_err_and (Rust 1.70) test the contents.

Panics: none, unless a closure panics.

Usage notes

  • map versus and_then: if your closure returns a plain value, use map. If it returns another Result, use and_then; otherwise you end up with a Result<Result<_, _>, _>.
  • map_err is how errors change type so that ? can convert them. For standard conversions, implementing From<SourceError> for MyError lets ? do it automatically.
  • Eager arguments: and(x), or(x) and map_or(d, f) evaluate their arguments immediately. Use the _else or closure forms for anything costly.
  • Order matters in chains: map_err placed before and_then only affects errors from earlier steps.
  • Closures consume the value (FnOnce). Use as_ref() first if you need the result afterwards.
  • and_then short-circuits. After the first Err, later closures never run, which is the same behavior as ?.
  • Prefer ? for readability once a chain needs more than two or three steps.