Sub topic 7
Transforming Results with map, map_err, and and_then
This chapter assumes you can read match on Result, you know closures at a basic level, and you have seen Option combinators such as map and and_then. Here you will use the same ideas on Result<T, E>, where there are two sides to transform: the success value and the error.
The two tracks of a Result
A Result is either Ok(T) or Err(E). Each combinator touches one track and passes the other through unchanged. Once a value is Err, the Ok-side combinators skip their closures, so a chain of them stops doing work at the first failure.
map: change the Ok value
map takes a closure FnOnce(T) -> U and returns Result<U, E>. The error type does not change.
fn main() {
let good: Result<u16, String> = Ok(80);
let bad: Result<u16, String> = Err(String::from("no value"));
println!("{:?}", good.map(|p| p + 1));
println!("{:?}", bad.map(|p| p + 1));
}This prints Ok(81) and then Err("no value"). The closure never runs for bad.
Use map when the closure cannot fail. If the closure itself returns a Result, use and_then instead (see below).
map_err: change the error
map_err takes FnOnce(E) -> F and returns Result<T, F>. The Ok value passes through untouched.
The most common use is to give a library error more context, or to turn it into the single error type your function returns:
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, String> {
s.trim()
.parse::<u16>()
.map_err(|e: ParseIntError| format!("invalid port {s:?}: {e}"))
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
}The output is:
Ok(8080)
Err("invalid port \"abc\": invalid digit found in string")The Err shows backslashes because {:?} prints a String in Debug form, which escapes quotes.
and_then: chain a fallible step
and_then takes FnOnce(T) -> Result<U, E> and returns Result<U, E>. If the receiver is Ok(v), it calls the closure with v and returns whatever the closure returns. If it is Err, it returns that error and skips the closure. Other languages call this flat_map or bind.
fn parse_port(s: &str) -> Result<u16, String> {
s.trim()
.parse::<u16>()
.map_err(|e| format!("invalid port {s:?}: {e}"))
}
fn check_port(p: u16) -> Result<u16, String> {
if p >= 1024 {
Ok(p)
} else {
Err(format!("port {p} is reserved"))
}
}
fn main() {
for input in ["8080", "80", "abc"] {
let result = parse_port(input).and_then(check_port);
println!("{input}: {result:?}");
}
}The three inputs produce Ok(8080), Err("port 80 is reserved"), and the parse error for abc. The function name check_port is passed directly because it matches FnOnce(u16) -> Result<u16, String>.
map versus and_then
Passing a fallible function to map compiles, but the result is nested:
fn check_port(p: u16) -> Result<u16, String> {
if p >= 1024 { Ok(p) } else { Err(format!("port {p} is reserved")) }
}
fn main() {
let ok: Result<u16, String> = Ok(8080);
let nested: Result<Result<u16, String>, String> = ok.clone().map(check_port);
let flat: Result<u16, String> = ok.and_then(check_port);
println!("{nested:?}");
println!("{flat:?}");
}This prints Ok(Ok(8080)) and then Ok(8080). If you see a type like Result<Result<..>> in a compiler message, you almost certainly wanted and_then.
The error type must stay the same in and_then
and_then can change the success type but not the error type. If parse::<u16>() returns Result<u16, ParseIntError> and your next step returns Result<u16, String>, the chain fails to compile with a type mismatch. Fix it by converting the error first with map_err:
fn parse_port(s: &str) -> Result<u16, String> {
s.trim().parse::<u16>().map_err(|e| format!("not a number: {e}"))
}
fn check_port(p: u16) -> Result<u16, String> {
if p >= 1024 { Ok(p) } else { Err(format!("port {p} is reserved")) }
}
fn address(s: &str) -> Result<String, String> {
parse_port(s)
.and_then(check_port)
.map(|p| format!("0.0.0.0:{p}"))
}
fn main() {
println!("{:?}", address("9000"));
println!("{:?}", address("22"));
}This prints Ok("0.0.0.0:9000") and then Err("port 22 is reserved"). Each combinator does one job: and_then runs a step that can fail, and map runs a step that cannot.
Supplying a fallback
Several methods leave the Result world by producing a plain value or a new Result.
| Method | Receives | Returns | Closure runs when |
|---|---|---|---|
| `unwrap_or(default)` | a ready value | `T` | never (the default is computed before the call) |
| `unwrap_or_else(f)` | `FnOnce(E) -> T` | `T` | the result is `Err` |
| `or_else(f)` | `FnOnce(E) -> Result<T, F>` | `Result<T, F>` | the result is `Err` |
| `ok()` | nothing | `Option<T>` | never (drops the error) |
unwrap_or evaluates its argument eagerly, even when the result is Ok. If the default is expensive to build or has side effects, use unwrap_or_else. The closure also receives the error, which lets you log it:
fn main() {
let port = "80x".parse::<u16>().unwrap_or_else(|e| {
eprintln!("falling back to 8080: {e}");
8080
});
println!("{port}");
}or_else is the error-side counterpart of and_then. Use it to try a second source when the first fails:
fn main() {
let value = "abc"
.parse::<u16>()
.or_else(|_| "9090".parse::<u16>());
println!("{value:?}");
}This prints Ok(9090).
Common mistakes
- Using
mapwith a closure that returnsResult, which produces nested results. Useand_then. - Forgetting
map_errbeforeand_then, which causes an error-type mismatch. - Calling
map_errand expecting it to change theOkvalue. It only touches the error. - Using
ok()and then ignoring theOption. This silently discards the reason for the failure. Keep theResultunless you truly do not care why it failed. - Writing
unwrap_or(expensive())whenunwrap_or_else(|_| expensive())was intended.
Exercises
Exercise
"42".parse::<u8>().map(|n| n.checked_sub(50)) has type Result<Option<u8>, ParseIntError>. How would you change the code so the result is Result<u8, String>, where a value below 50 gives the error "too small"?
Show answer
Convert the parse error first, then use andthen for the step that can fail: "42".parse::<u8>().maperr(|e| e.tostring()).andthen(|n| n.checkedsub(50).okorelse(|| String::from("too small"))) Here 42 - 50 underflows, so checkedsub returns None, okorelse turns it into Err("too small"), and the final type is Result<u8, String>.
Exercise
What does Err::<u16, &str>("bad").map(|p| p + 1).map_err(|e| e.len()) evaluate to, and does the map closure run?
Show answer
It evaluates to Err(3). The map closure does not run because the value is Err. The map_err closure runs and replaces "bad" with its length, 3.