Lesson 9 of 11
Enums and match
Model different states and handle each one with a match arm.
main.rs
enum Download { Waiting, Ready(u32),}fn main() { for state in [Download::Waiting, Download::Ready(12)] { match state { Download::Waiting => println!("Waiting"), Download::Ready(size) => println!("{size} KB"), } }}Program state
- Waiting
- No data
- Ready
- Size in KB
Step 1 of 5
Download has one variant for waiting and one for a completed file.
What’s happening
An enum defines the possible variants of a type. A Download value here is either Waiting or Ready. The Ready variant carries a file size as a u32.
A match compares a value to each pattern in turn and runs the first arm that matches. A pattern like Download::Ready(size) binds the data inside that variant to size. Rust checks that every possible case has a matching arm.
See an example the compiler rejects
enum Download { Waiting, Ready(u32),}fn main() { for state in [Download::Waiting, Download::Ready(12)] { match state { Download::Waiting => println!("Waiting"), } }}The match only handles Waiting. The compiler requires an arm that can also handle Ready and its size.