Rust 1.99 (2024 edition) reference · Option and Result
Rust Option::map, and_then and filter Method
Transform the value inside an Option without unwrapping it, chain optional steps, or keep it only if a condition holds.
Rust 1.99 (2024 edition)
Syntax
fn map<U>(self, f: F) -> Option<U> fn and_then<U>(self, f: F) -> Option<U> fn filter(self, p: P) -> Option<T>
Parameters
| Parameter | Description |
|---|---|
map |
Apply a function to Some(v). |
and_then |
Chain a function that itself returns an Option. |
filter |
None unless the predicate holds. |
ok_or(err) |
Turn an Option into a Result. |
Examples
fn main() {
let input = Some(" 42 ");
let n: Option<i32> = input.map(str::trim).and_then(|s| s.parse().ok());
println!("{n:?}");
let even = n.filter(|v| v % 2 == 0);
println!("{even:?}");
let missing: Option<&str> = None;
println!("{:?}", missing.map(|s| s.len()));
}
Output
Some(42) Some(42) None
Run this on your computer — see “Get Started” for setup.
fn main() {
fn find_user(id: u32) -> Option<&'static str> { if id == 1 { Some("ana") } else { None } }
let r: Result<&str, String> = find_user(2).ok_or(format!("user {} not found", 2));
println!("{r:?}");
}
Output
Err("user 2 not found")Run this on your computer — see “Get Started” for setup.
Related
Option::unwrap_or and friends· Get the value out of an Option with a default, a computed default, or the type's default instead of panicking with unwrap.Result::map_err, unwrap_or_else and ok· Convert or recover from errors: change the error type, fall back to a value, or discard the error as an Option.- Rust Enums and Option · tutorial