Sub topic 7
Transforming Results with map, map_err, and and_then
This chapter assumes you know Result<T, E>, match, closures, and how Option combinators such as map and and_then work. Result combinators follow the same ideas. They apply to the Ok value, to the Err value, or to both in sequence, without a match each time.
Three methods, three targets
| Method | Runs on | Closure signature | Result type |
|---|---|---|---|
| `map` | `Ok(t)` | `T -> U` | `Result<U, E>` |
| `map_err` | `Err(e)` | `E -> F` | `Result<T, F>` |
| `and_then` | `Ok(t)` | `T -> Result<U, E>` | `Result<U, E>` |
Each method leaves the other variant untouched. map passes an Err through unchanged, and map_err passes an Ok through unchanged.
map: change the success value
Use map when the closure cannot fail. It wraps the closure's return value in Ok for you.
fn main() {
let doubled = "21".parse::<i32>().map(|n| n * 2);
println!("{doubled:?}");
let failed = "x".parse::<i32>().map(|n| n * 2);
println!("{failed:?}");
}The first line prints Ok(42). The second prints the original Err(ParseIntError { kind: InvalidDigit }), because map skips errors.
map_err: change the error
map_err rewrites the error type. This is how you fit one function's error into the error type of another.
fn parse_port(s: &str) -> Result<u16, String> {
s.trim()
.parse::<u16>()
.map_err(|e| format!("invalid port {s:?}: {e}"))
}
fn main() {
println!("{:?}", parse_port(" 8080 "));
println!("{:?}", parse_port("99999"));
}The error type changes from ParseIntError to String. The success path is not affected.
and_then: chain fallible steps
If the closure itself returns a Result, map produces a nested Result<Result<_, _>, _>. and_then flattens that. It runs the next step only when the previous one succeeded, and it stops at the first Err.
fn parse_port(s: &str) -> Result<u16, String> {
s.trim().parse::<u16>().map_err(|e| e.to_string())
}
fn check_unprivileged(port: u16) -> Result<u16, String> {
if port > 1024 {
Ok(port)
} else {
Err(format!("port {port} is reserved"))
}
}
fn main() {
println!("{:?}", parse_port("8080").and_then(check_unprivileged));
println!("{:?}", parse_port("80").and_then(check_unprivileged));
println!("{:?}", parse_port("abc").and_then(check_unprivileged));
}Both steps use String as the error type. and_then cannot change E, so the types must already match. Apply map_err first if they do not.
Common errors
- Using
mapwith a closure that returnsResult. You get a nested type that is hard to use. Switch toand_then. - Using
and_thenwith mismatched error types. The compiler reports a type mismatch onE. Insertmap_errbefore the chain. - Forgetting that the closure in
map_errreceives the error by value. Format it or wrap it, as shown above.
Exercise
What is the type of "5".parse::<i32>().map(|n| n.checked_add(1)), and which method would you use to get a plain Result<i32, ParseIntError> that fails when addition overflows? Assume the overflow case should produce a ParseIntError is not possible, so the error type must be changed first.
Show answer
The type is Result<Option<i32>, ParseIntError>, because map wraps the Option returned by checked_add in Ok. To get a flat Result<i32, String>, first change the error with map_err(|e| e.to_string()). Then use and_then(|n| n.checked_add(1).ok_or(String::from("overflow"))), which converts the Option into a Result and flattens it.