Option<T> is Some(value) or None. Iterator searches return Option, and match handles both cases.

Program

Play the program to find the first value over 15.

option.rs
Replay: real traced execution (multi-file project)
fn main() {
    let nums = vec![10, 20, 30];
    let found = nums.iter().find(|&&n| n > 15);
    let value = match found {
        Some(n) => *n,
        None => 0,
    };
    println!("{value}");
}
  1. nums ← [10, 20, 30], found ← Some(20), value ← 20

    1fn main() {2    let num→ [10, 20, 30]s = vec![10, 20, 30];3    let foun→ Some(20)d = nums.iter().find(|&&n| n > 15);4    let valu→ 20e = match founSome(20)d {5        Some(n) => *n,6        None => 0,7    };8    println!("{value}");9}
    output20

Follow the Search

  1. The list starts with several numbers.
  2. find checks each number until one matches the rule.
  3. A match becomes Some(value).
  4. No match becomes None.
  5. match gives each case its own print path. | Search result | Meaning | | --- | --- | | Some(value) | A matching number was found. | | None | The search reached the end without a match. |
Option `Option<T>` models a value that may be absent.
find `find` returns `Some` for the first match, else `None`.
match Handling `Some` and `None` is required to read the value.

Exercise: option.rs

Search a list for the first even value over 20, then print separate Some and None messages