← 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.

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
fn main() {
    let some_number: Option<i32> = Some(5);
    let no_number: Option<i32> = None;
    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
fn main() {
    let maybe_age: Option<u32> = Some(25);
    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
fn main() {
    let missing: Option<i32> = None;
    let value = missing.unwrap_or(0);
    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
fn find_even(numbers: &[i32]) -> Option<i32> {
    for &n in numbers {
        if n % 2 == 0 {
            return Some(n);
        }
    }
    None
}

fn main() {
    let nums = [1, 3, 4, 7];
    match find_even(&nums) {
        Some(n) => println!("Found even number: {}", n),
        None => println!("No even number found"),
    }
}
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.