std-method

Result::map_err

Convert an error into a new type or add context while preserving successful values. The closure runs only for Err; retain useful details rather than replacing every failure with an uninformative message. Expected stdout (not executed): Err("invalid quantity") Common mistake: Expecting map_err to fix the underlying failure and produce Ok.

Formal Syntax & Structure

rust syntaxrust
fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F>

Working Example

Example Snippetrust
fn main() {    let parsed = "x".parse::<u32>().map_err(|_| "invalid quantity");    println!("{parsed:?}");}
Rust Reference