Option for absent values
Quick answer
Option<T> represents either a present value Some(T) or an absent value None. It lets a function return missing data without inventing a sentinel such as -1 that could also be legitimate data.
Handle both variants
The T stands for the contained type, for example Option<i32>. A match extracts the value from Some and separately handles None. is_some() and is_none() check presence. unwrap_or(default) consumes the option and returns its value or a default. Avoid calling unwrap on uncertain data because None causes a panic.
fn first(values: &[i32]) -> Option<i32> { if values.is_empty() { None } else { Some(values[0]) }}fn main() { for result in [first(&[7, 9]), first(&[])] { match result { Some(n) => println!("reading: {n}"), None => println!("no reading"), } }}Expected stdout (not executed):
reading: 7no readingThe empty sequence is handled explicitly without invalid indexing.
fn main() { let stored: Option<u32> = None; let configured = Some(5u32); println!("{} {}", stored.unwrap_or(3), configured.unwrap_or(3));}Expected stdout (not executed):
3 5The default applies only to None; Some preserves its contained value.
Common mistake
Some(0) and None are distinct. Do not treat zero as absence unless your application explicitly defines that policy.
Try it yourself
Write a function returning Some(n) for nonnegative integers and None otherwise. Test it with -1, 0 and 5.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Option for absent values — practice quiz
Choose one answer per question, then review the explanation.
What does `Some(0).is_some()` return?
What does `None::<i32>.unwrap_or(7)` return?
What is the risk of calling unwrap on an uncertain Option?