On this page
  1. Option
  2. Availability
  3. Syntax & Overview
  4. Notes & Pitfalls
  5. Example

Option

Prev: builtins | Up: builtins | Next: Result
Rel: builtins, Ownership, Borrowing & Lifetimes
Ref: Rust Docs — Option
Tags: #public #prog #rust #builtins #tier/core


Availability

Built-in / Prelude (Prelude Enum) — available with zero use imports.

Syntax & Overview

enum Option<T> { None, Some(T) }

Replaces null with an explicit type-checked sum type representing presence (Some(T)) or absence (None).

Notes & Pitfalls

Example

fn find_even(nums: &[i32]) -> Option<i32> {
    nums.iter().copied().find(|n| n % 2 == 0)
}

fn main() {
    assert_eq!(find_even(&[1, 3, 4, 5]), Some(4));
    assert_eq!(find_even(&[1, 3]).unwrap_or(-1), -1);
}

Linked from

Related notes