Course contentsShow
← Rust
Lesson 823 of 1,9107. Error Handling PatternsFree lesson

Mapping Success Values

Transform inner Result values using functional combinators without breaking the error flow.

In this lesson, you will learn how to transform the successful data inside a Result without needing to manually unpack or re-wrap the value.

The Problem with Manual Unwrapping

When working with functions that return a Result<T, E>, you often find yourself in a situation where the T (the success value) isn't exactly what you need for the next step of your logic. Perhaps you have a Result<String, MyError> but you need the length of that string, or you need to convert it into a different type.

Before today, you might have been tempted to write a match statement:

let result: Result<String, MyError> = get_username();

let length = match result {
    Ok(name) => Ok(name.len()),
    Err(e) => Err(e),
};

This pattern works, but it is verbose and repetitive. If you have many steps, your code becomes cluttered with boilerplate Ok and Err wrapping.

Enter .map()

Rust provides a functional combinator called .map() specifically to handle this. It allows you to apply a transformation to the "happy path" (the Ok value) while leaving the error branch untouched. If the result is an Err, .map() simply passes it through, ignoring your transformation logic.

Here is how much cleaner your code becomes:

let name_result: Result<String, MyError> = get_username();

// We transform the String into a usize without touching the Error
let length_result: Result<usize, MyError> = name_result.map(|name| name.len());

Why This Matters

By using .map(), you maintain the "flow" of your error handling. You don't have to break your chain of logic to perform simple data transformations. It treats the Result like a container that either holds a value you want to process or an error you want to propagate. Because .map() consumes the original Result and returns a new one, it fits perfectly into the functional style of Rust, keeping your intentions clear and your code concise.

Key Takeaway: Use .map() to transform the success value inside a Result while automatically preserving the error state, keeping your code clean and your error flow uninterrupted.