RUST / CHAPTER 06
Enums and exhaustive decisions
IntermediateRepresent absent values and handle every possibility explicitly.
By the end of this chapter
- Model optional values with Option
- Extract data using patterns
- Write exhaustive match expressions
The idea
Enter with expressions and function signatures understood. An enum describes a value that is exactly one of several variants. A variant may contain data, as Some carries a value inside Option<T>. None represents absence without choosing a special integer or string as a sentinel. This lets zero, negative numbers, and empty text remain legitimate results.
A match expression selects the first matching arm and can produce a result. Patterns can extract the data from a variant, while exhaustiveness checking requires every possible case to be covered. This makes new variants and forgotten failure cases harder to ignore. Use an explicit None branch when absence needs its own behavior; do not unwrap merely to silence the compiler when missing data is expected.
fn describe(n:Option<i32>)->String {
match n {Some(v)=>format!("value {}",v),None=>String::from("missing")}
}
fn main(){println!("{}",describe(Some(0)));}value 0
Some(0) is present data, so the first arm binds v to zero. It does not take the absence branch.
Try it yourself
Represent a lookup that may return an empty string using Option<String>, and explain the difference from None.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING