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)

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
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

Example 1
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.

Option to Result with ok_or
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.

Was this page helpful?