Sub topic 6
Transforming Options with map, and_then, filter, and unwrap_or
This chapter assumes you know how Option<T> works, how to use match, if let, and let else, and the basics of closures. Combinators are methods on Option that transform a value without a match. When the value is None, they pass the None along untouched.
map: change the value inside
map applies a function to the Some value and wraps the result in a new Some. None stays None. The closure never runs for None.
unwrap_or unwraps the option and supplies a default for None. Chained together, the two methods make a short pipeline.
fn main() {
let name: Option<&str> = Some(" Ferris ");
let len = name.map(str::trim).map(str::len).unwrap_or(0);
println!("{len}");
}This prints 7. If name were None, both map calls would be skipped and len would be 0.
and_then: chain steps that can also be missing
If the closure itself returns an Option, map gives you Option<Option<T>>. Use and_then instead. It calls the closure and returns its Option as is, without adding another layer.
fn first_char_digit(s: Option<&str>) -> Option<u32> {
s.and_then(|t| t.chars().next())
.and_then(|c| c.to_digit(10))
}
fn main() {
println!("{:?}", first_char_digit(Some("7up")));
println!("{:?}", first_char_digit(Some("up")));
println!("{:?}", first_char_digit(Some("")));
println!("{:?}", first_char_digit(None));
}This prints Some(7), None, None, and None. Each step can fail, and the first failure ends the chain.
filter: keep a value only if it passes a test
filter takes a predicate. If the option is Some and the predicate returns true, you keep the value. Otherwise you get None.
fn main() {
let port = "80x".parse::<u16>().ok().filter(|p| *p > 1024).unwrap_or(8080);
println!("{port}");
}"80x" fails to parse, so ok() produces None and the default 8080 is used. A valid port such as "80" would also fall back, because filter rejects values of 1024 or below.
Choosing a default
| Method | Default is | Use when |
|---|---|---|
| `unwrap_or(v)` | a value, always built | the default is cheap, such as `0` |
| `unwrap_or_else(f)` | a closure, run only for `None` | building the default costs something |
| `unwrap_or_default()` | `Default::default()` | the type has a sensible default |
fn main() {
let nickname: Option<String> = None;
let a = nickname.clone().unwrap_or(String::from("guest"));
let b = nickname.clone().unwrap_or_else(|| format!("guest-{}", 42));
let c = nickname.unwrap_or_default();
println!("{a} {b} [{c}]");
}This prints guest guest-42 []. With unwrap_or, the String is allocated even when the option is Some. unwrap_or_else avoids that cost.
Common errors
- Using
mapwith a closure that returns anOption. You getOption<Option<T>>. Switch toand_then. - Using
unwrap_or(expensive()). The call runs every time, even forSome. Useunwrap_or_else. - Calling a combinator on a non-
Copyoption you need later. These methods takeselfby value and move it. Chapter material onas_refcovers this, andcloneis a stopgap.
Exercise
Write a function double_even(n: Option<i32>) -> i32 that doubles the number if it is even and returns -1 in every other case, including None. Use only combinators, with no match.
Show answer
fn doubleeven(n: Option<i32>) -> i32 { n.filter(|x| x % 2 == 0).map(|x| x * 2).unwrapor(-1) }