← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 2 of 7

The Option Type

Option is Rust's safe way of saying "there might be a value here, or there might be nothing" without ever using null.
Syntax
rust
enum Option<T> {
    Some(T),
    None,
}

let value: Option<Type> = Some(v);

What Is Option

Option<T> is an enum with two variants: Some(value) when a value is present, and None when it is absent. It replaces the concept of null found in many other languages.

Example: What Is Option

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `some_number` (a `Option<i32>`), set to `Some(5)`
    let some_number: Option<i32> = Some(5);
    // Declare an immutable variable `no_number` (a `Option<i32>`), set to `None`
    let no_number: Option<i32> = None;
    // Print "{:?} and {:?}" to the console, substituting in `some_number, no_number` (with a trailing newline)
    println!("{:?} and {:?}", some_number, no_number);
}

Matching on Option

match lets you safely handle both possibilities of an Option, extracting the inner value in the Some case and handling absence explicitly in the None case.

Example: Matching on Option

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `maybe_age` (a `Option<u32>`), set to `Some(25)`
    let maybe_age: Option<u32> = Some(25);
    // Match on `maybe_age` and branch by pattern
    match maybe_age {
        Some(age) => println!("Age is {}", age),
        None => println!("No age provided"),
    }
}

Using unwrap_or for a Default

.unwrap_or(default) returns the inner value if present, or a fallback default value if the Option is None, avoiding the need for a full match for simple cases.

Example: Using unwrap_or for a Default

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `missing` (a `Option<i32>`), set to `None`
    let missing: Option<i32> = None;
    // Declare an immutable variable `value`, set to `missing.unwrap_or(0)`
    let value = missing.unwrap_or(0);
    // Print "Value: {}" to the console, substituting in `value` (with a trailing newline)
    println!("Value: {}", value);
}

Functions Returning Option

Functions that might not have a meaningful result to return use Option<T> as their return type, forcing every caller to explicitly handle the possibility of None.

Example: Functions Returning Option

markup
// Define the function `find_even` taking `numbers` and returning a `Option<i32>`
fn find_even(numbers: &[i32]) -> Option<i32> {
    // Loop over `numbers`, binding each item to `&n`
    for &n in numbers {
        // Check whether `n % 2 == 0`
        if n % 2 == 0 {
            // Return `Some(n)` from this function
            return Some(n);
        }
    }
    None
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `nums`, set to `[1, 3, 4, 7]`
    let nums = [1, 3, 4, 7];
    // Match on `find_even(&nums)` and branch by pattern
    match find_even(&nums) {
        Some(n) => println!("Found even number: {}", n),
        None => println!("No even number found"),
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to use an Option<T> value directly as if it were a T, without unwrapping or matching it first.
  2. Calling .unwrap() on an Option that might be None, which panics the program at runtime.
  3. Assuming Rust has a null value like other languages -- Rust deliberately has no null; Option::None replaces that concept safely.
Chapter Summary
  • Option<T> represents a value that is either Some(value) or None.
  • Rust has no null pointers; Option forces you to explicitly handle the 'no value' case.
  • match, if let, and combinator methods like .unwrap_or() are common ways to safely handle an Option.
  • Using Option moves the possibility of 'no value' into the type system, catching missing-value bugs at compile time.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.