Lesson 12 of 20

The Option Type

Option<T>

Rust has no null. Instead, the absence of a value is represented with Option<T>:

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

This is part of the standard library and is always in scope.

Creating Options

let some_number: Option<i32> = Some(5);
let absent: Option<i32> = None;

Using Options

// match — exhaustive handling
match some_number {
    Some(n) => println!("Got {}", n),
    None => println!("Nothing"),
}

// unwrap — panics if None
let n = some_number.unwrap();

// unwrap_or — provide a default
let n = some_number.unwrap_or(0);

// map — transform the value if Some
let doubled = some_number.map(|n| n * 2); // Some(10)

// if let — concise pattern match for one variant
if let Some(n) = some_number {
    println!("Got {}", n);
}

The ? Operator

In functions that return Option, use ? to propagate None automatically:

fn first_even_doubled(v: &[i32]) -> Option<i32> {
    let first_even = v.iter().find(|&&x| x % 2 == 0)?; // returns None if not found
    Some(first_even * 2)
}

Your Task

Implement four functions:

  1. safe_divide(a: f64, b: f64) -> Option<f64> — returns None if b is 0.
  2. first_even(numbers: &[i32]) -> Option<i32> — returns the first even number.
  3. safe_sqrt(x: f64) -> Option<f64> — returns None for negative inputs.
  4. double_first(v: &[i32]) -> Option<i32> — returns double the first element, or None if empty.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.