Enums (enumerations) represent a value that can be one of several distinct variants. They're incredibly powerful in Rust for expressing types with limited possibilities.
letx: Option<i32> = Some(5);
lety: Option<i32> = None;
// is_some() and is_none()if x.is_some() {
println!(\"x has a value\");
}
// unwrap() - panics if None
let val = x.unwrap(); // 5
// let bad = y.unwrap(); // panics!
// unwrap_or() - provides default
let val2 = y.unwrap_or(0); // 0
// map() - transform the value
let doubled = x.map(|n| n * 2); // Some(10)
Practical Example
enumStatus {
Active,
Inactive,
Pending { days_until: u32 },
}
fnprocess_status(status: Status) {
match status {
Status::Active => println!(\"Ready to go!\"),
Status::Inactive => println!(\"Offline\"),
Status::Pending { days_until } => {
println!(\"Will activate in {} days\", days_until);
}
}
}
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities