Sub topic 6
Transforming Options with map, and_then, filter, and unwrap_or
This chapter assumes you know basic Rust syntax, enums and match, closures, and the shape of Option<T> (Some(value) or None). The previous chapters showed how to take an Option apart with match, if let, and let else. Here you will transform one without unpacking it, which keeps the code flat and avoids repeated match blocks.
The idea: transform the inside, keep the wrapper
Most Option methods follow one rule. If the value is Some, run a function on the contents. If it is None, skip the function and stay None. A missing value passes through the whole chain untouched, and you only decide what to do about it at the end.
| Method | Closure receives | Closure returns | Result |
|---|---|---|---|
| `map` | the value `T` | a plain `U` | `Option<U>` |
| `and_then` | the value `T` | an `Option<U>` | `Option<U>` |
| `filter` | a reference `&T` | a `bool` | `Option<T>` |
| `unwrap_or` | nothing, takes a value | not applicable | `T` |
| `unwrap_or_else` | nothing | a `T` | `T` |
map: change the value
map applies a function to the contents of Some and wraps the result in a new Some.
fn main() {
let name: Option<&str> = Some(" Ferris ");
let len = name.map(str::trim).map(str::len).unwrap_or(0);
println!("{len}");
let missing: Option<&str> = None;
println!("{:?}", missing.map(str::len));
}This prints 6 and then None. You can pass a function path such as str::trim where a closure is expected, as long as the signature fits.
map takes self by value. The original Option is consumed unless its contents are Copy. For an Option<String> you want to keep using, call as_ref() first, which a later chapter covers.
and_then: chain steps that can also fail
If the closure itself returns an Option, map produces a nested Option<Option<U>>. and_then (called flatMap in some languages) removes the extra layer.
fn first_digit(s: &str) -> Option<u32> {
s.chars().next().and_then(|c| c.to_digit(10))
}
fn main() {
println!("{:?}", first_digit("7up"));
println!("{:?}", first_digit("up7"));
println!("{:?}", first_digit(""));
let nested: Option<Option<u32>> = Some("7up").map(first_digit);
println!("{:?}", nested);
println!("{:?}", nested.flatten());
}The output is Some(7), None, None, Some(Some(7)), and Some(7). Each of the three first_digit calls can fail at a different step. next() returns None for an empty string, and to_digit returns None for a non-digit.
Use map when the closure cannot fail, and and_then when it can.
filter: keep the value only if it passes a test
filter turns a Some into None when the predicate returns false. The predicate receives a reference, so you often dereference with *.
fn main() {
let even = Some(4).filter(|n| n % 2 == 0);
let odd = Some(5).filter(|n| n % 2 == 0);
println!("{even:?} {odd:?}");
let port = "80x".parse::<u16>().ok().filter(|p| *p > 1024).unwrap_or(8080);
println!("{port}");
}This prints Some(4) None and then 8080. A None input stays None, so filter never turns an absent value into a present one.
Leaving the Option: the unwrap_or family
At the end of a chain you usually want a plain value. These methods supply a fallback for None and never panic.
unwrap_or(default)takes a ready-made value.unwrap_or_else(f)calls a closure only when the value isNone.unwrap_or_default()usesDefault::default()for the type, such as0,"", or an emptyVec.map_or(default, f)maps and unwraps in one step.map_or_else(default_fn, f)is the same with a lazily computed default.
The difference between unwrap_or and unwrap_or_else is when the default is computed.
fn default_name() -> String {
println!("computing default");
String::from("guest")
}
fn main() {
let a = Some(String::from("ana")).unwrap_or(default_name());
let b = Some(String::from("ana")).unwrap_or_else(default_name);
println!("{a} {b}");
let doubled = Some(3).map_or(0, |x| x * 2);
let empty: String = None.unwrap_or_default();
println!("{doubled} [{empty}]");
}computing default prints once, from the unwrap_or line. Arguments are evaluated before the call, so default_name() runs even though the value is Some. unwrap_or_else receives the function itself and never calls it here.
Putting a chain together
The pieces compose into a single readable pipeline. This function reads an optional port setting and falls back to 8080 for anything unusable.
fn port_from(input: Option<&str>) -> u16 {
input
.map(str::trim)
.and_then(|s| s.parse::<u16>().ok())
.filter(|p| *p >= 1024)
.unwrap_or(8080)
}
fn main() {
println!("{}", port_from(Some(" 3000 ")));
println!("{}", port_from(Some("80")));
println!("{}", port_from(Some("abc")));
println!("{}", port_from(None));
}The output is 3000, 8080, 8080, 8080. The ok() call converts a Result into an Option. The chapter on moving between Option and Result covers it. It also discards the parse error, which is a deliberate loss of information here.
Common mistakes
- Using
mapwhen the closure returns anOption. The type becomesOption<Option<T>>, and the compiler error shows up later, where you use the value. Switch toand_thenor callflatten(). - Forgetting that
filterreceives a reference.|p| p > 1024fails to compile forOption<u16>. Write*p > 1024or|&p| p > 1024. - Calling
unwrap_or(expensive()). The expensive call always runs. Useunwrap_or_else. - Moving out of a borrowed
Option.self.name.map(...)on a&selffield does not compile when the field is notCopy. Useself.name.as_ref().map(...)instead. - Over-chaining. A chain of six closures can be harder to read than a short
match. When a branch needs several statements or early returns, prefermatchorlet else.
Exercise
Write fn clean_len(input: Option<&str>) -> Option<usize> that trims the text and returns its length, but returns None if the trimmed text is empty. Use only map and filter. What does clean_len(Some(" ")) return?
Show answer
input.map(str::trim).filter(|s| !s.isempty()).map(str::len). The call `cleanlen(Some(" ")) returns None. The first map produces Some(""), the filter predicate returns false for the empty string, and the final map is skipped. For Some(" hi ") the result is Some(2)`.
Exercise
A teammate writes let n = text.parse::<i32>().ok().map(|v| v.checked_mul(2)).unwrap_or(0); and gets a type error. Why, and what is the fix?
Show answer
checked_mul returns an Option<i32>, so map produces Option<Option<i32>>, and unwrap_or(0) expects an Option<i32> as the default. Replace map with and_then so the result is Option<i32>, giving text.parse::<i32>().ok().and_then(|v| v.checked_mul(2)).unwrap_or(0).