Rust Reference ยท Option and Result
Option map, and_then and friends
Reference for Option transformation methods in Rust: map, map_or, map_or_else, and_then, is_some_and and inspect, with chains, closures and flattening nested options.
map and and_then transform the value inside an Option without unwrapping it by hand. If the option is None, the closure never runs and None comes out. If it is Some, the closure receives the inner value and produces the result.
The difference is the closure's return type. map takes a closure returning a plain U and wraps it again, giving Option<U>. and_then takes a closure that already returns an Option<U> and does not wrap it again, which is what you want to chain steps that can each fail.
Some(3).map(|n| n + 1); // Some(4) Some("42").and_then(|s| s.parse().ok()); // Some(42)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Option<T> { pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U>; pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U; pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U; pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U>; pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool; pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self; }
| Method | Some(x) |
None |
|---|---|---|
map(f) |
Some(f(x)) |
None |
map_or(d, f) |
f(x) |
d |
map_or_else(d, f) |
f(x) |
d() |
and_then(f) |
f(x) (already an Option) |
None |
is_some_and(f) |
f(x) |
false |
inspect(f) |
calls f(&x), returns the option |
None |
Returns: an Option<U> for map and and_then, a plain U for map_or and map_or_else, a bool for is_some_and.
Usage notes
- Pick
and_thenwhen the closure returnsOption. If you findOption<Option<U>>in your types, you usedmapwhereand_thenbelongs (or call.flatten()). - Closures consume. All of these take
self. Calling.mapon anOption<String>moves the string into the closure; useas_ref(),as_deref()oras_mut()first to work with references. - Method references.
map(str::len),map(String::from)andand_then(|s| s.parse().ok())keep chains tidy. map_orevaluates its default eagerly, so usemap_or_elsewhen the default is costly.- Replacing
match. AmatchwhoseNonearm just returnsNoneis amaporand_then. When both arms contain real logic, amatchis clearer than a chain. is_some_andreplacesmap_or(false, ...), and is stable since Rust 1.70.inspectwas added in 1.76.- Errors. To keep the reason for a failure, convert with
ok_orand useResultcombinators instead.