Rust Enums and Pattern Matching
Represent different states without a loose collection of flags.
How it works
An enum describes a value that is one of several named variants. Variants can carry different data, and match can require each state to be handled. This can express a checked-out tray differently from an available one instead of allowing contradictory Boolean combinations. The type still needs transition rules when state changes depend on external events.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
enum TrayState { Available(u32), Empty }
let states = [TrayState::Available(8), TrayState::Empty];
let total: u32 = states.iter().map(|state| match state { TrayState::Available(n) => *n, TrayState::Empty => 0 }).sum();
assert_eq!(total, 8);
println!("Available packets across states: {total}");
}
Expected result
Available packets across states: 8
The available variant carries a count, while empty carries none. The match accounts for both states before summation. Adding a variant can force relevant match expressions to be revisited. A catch-all arm can be appropriate, but it also removes some of that explicit coverage pressure.
Primary technical reference: Rust documentation.