Rust Tutorial · Structs, Enums and Collections · Lesson 14 of 29

Rust Enums and Option

Model choices with enums that carry data, and handle missing values with Option instead of null.

Create a free account to save this page, take notes and track your progress. Sign in

Enums with data

Each variant of an enum can hold different data, which makes them ideal for states and messages:

Enums carrying data
enum Payment {
    Card { last4: String },
    Transfer(String),
    Cash,
}

fn describe(payment: &Payment) -> String {
    match payment {
        Payment::Card { last4 } => format!("card ending {last4}"),
        Payment::Transfer(iban) => format!("transfer from {iban}"),
        Payment::Cash => "cash".to_string(),
    }
}

fn main() {
    let payments = [Payment::Card { last4: "4242".into() }, Payment::Transfer("DE89...".into()), Payment::Cash];
    for p in &payments {
        println!("{}", describe(p));
    }
}

Output

card ending 4242
transfer from DE89...
cash

Run this on your computer — see “Get Started” for setup.

Option instead of null

Rust has no null. A value that may be missing is an Option<T>: Some(value) or None. The compiler makes you handle both cases.

Option<T>
fn find_price(item: &str) -> Option<f64> {
    match item {
        "mug" => Some(8.5),
        "teapot" => Some(24.0),
        _ => None,
    }
}

fn main() {
    for item in ["mug", "lamp"] {
        match find_price(item) {
            Some(price) => println!("{item}: {price}"),
            None => println!("{item}: not sold here"),
        }
    }
    let total = find_price("mug").unwrap_or(0.0) + find_price("lamp").unwrap_or(0.0);
    println!("total: {total}");
    let doubled = find_price("teapot").map(|p| p * 2.0);
    println!("{doubled:?}");
}

Output

mug: 8.5
lamp: not sold here
total: 8.5
Some(48.0)

Run this on your computer — see “Get Started” for setup.

Test yourself

How does Rust represent a value that might be missing?

  1. null
  2. Option<T>: Some(value) or None
  3. An empty string
  4. undefined
Show answer

Answer: Option<T>: Some(value) or None

Was this page helpful?