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.
Enums with data
Each variant of an enum can hold different data, which makes them ideal for states and messages:
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.
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?
nullOption<T>: Some(value) or NoneAn empty stringundefined
Show answer
Answer: Option<T>: Some(value) or None