The reading queue will accept commands such as add 7 Rust, finish 7 and list. They need different data: adding needs an ID and a title, finishing needs only an ID, and listing needs nothing. One struct with every possible field would allow nonsense, such as a list command that carries a title, and every reader would have to guess which fields matter. In the beginner course, enum variants were plain names. Here each variant carries exactly the data it needs, and nothing else.
Add { id: u32, title: String } is a struct-like variant with named fields. Finish(u32) is a tuple-like variant. List has no data. A match names a variant and binds the fields that exist on it, so you can only reach a title in the arm where a title exists.
Predict and run
Which fields are available in each arm? Can main describe the same add command twice?
enum Command {
Add { id: u32, title: String },
Finish(u32),
List,
}
fn describe(command: &Command) {
match command {
Command::Add { id, title } => println!("Add #{id}: {title}"),
Command::Finish(id) => println!("Finish #{id}"),
Command::List => println!("List books"),
}
}
fn main() {
let command = Command::Add { id: 7, title: String::from("Rust") };
describe(&command);
describe(&command);
describe(&Command::Finish(7));
describe(&Command::List);
}Check your prediction
Add #7: Rust
Add #7: Rust
Finish #7
List booksdescribe takes &Command, so it only borrows. When you match on a reference, the bindings become references too: inside the first arm, id is a &u32 and title is a &String. Nothing moves out, so command is still whole for the second call. Try adding a Remove(u32) variant to the enum and run. Predict which line the compiler points at.
The compiler checks every variant
A match must cover every possible value. After adding Remove(u32), the run stops with error[E0004]: non-exhaustive patterns: &Command::Remove(_) not covered, and it names the match in describe. In a larger program, that error lists every place that must learn about the new command. This is the main reason to prefer an enum over a string such as "remove": a new string is just a typo waiting to happen, while a new variant is a list of places to update.
A catch-all _ => ... arm would silence that error. Use one only when the remaining cases truly share one behavior, because it also hides future variants.
Borrowing or consuming in a match
Matching on command itself, instead of &command, moves the fields you bind into the arm. That is useful when you want to keep the owned String, but the original value is then partly moved:
let command = Command::Add { id: 7, title: String::from("Rust") };
match command {
Command::Add { id, title } => println!("{id} {title}"),
_ => {}
}
describe(&command);This fails with error[E0382]: borrow of partially moved value: command, because title now lives in the arm. When moving is the goal, make it explicit with a function that takes the value.
enum Command {
Add { id: u32, title: String },
Finish(u32),
List,
}
fn into_title(command: Command) -> Option<String> {
match command {
Command::Add { title, .. } => Some(title),
Command::Finish(_) | Command::List => None,
}
}
fn main() {
let commands = [
Command::Add { id: 7, title: String::from("Rust") },
Command::Finish(7),
Command::List,
];
for command in commands {
match into_title(command) {
Some(title) => println!("Owned title: {title}"),
None => println!("No title"),
}
}
}Owned title: Rust
No title
No title{ title, .. } binds one field and ignores the rest. Command::Finish(_) | Command::List joins two patterns with | in one arm, and _ ignores the ID. Looping over the array by value moves each command into into_title, which hands back the String without copying it. Notice that no _ => arm was needed, so a new variant would still be reported here.
Borrow to look, take by value to keep
Write fn f(x: &Command) when you only need to read the fields. Take Command by value only when the function must keep or return owned data from it.
Practice
Your turn
Write a function show(event: &Event) for an enum with Queued(String) and Completed { id: u32, pages: u32 }. Call it on both events by reference, then print Still have: Rust using the first event afterward, so you prove it was not moved. Expected output: Queued: Rust, Completed #7 (120 pages), Still have: Rust.
enum Event {
Queued(String),
Completed { id: u32, pages: u32 },
}
fn main() {
let queued = Event::Queued(String::from("Rust"));
let finished = Event::Completed { id: 7, pages: 120 };
// Show both events by reference.
}Hint 1: the idea
Each arm's pattern copies the shape of its variant: parentheses for a tuple-like variant, braces with field names for a struct-like one.
Hint 2: a first step
Use Event::Queued(title) and Event::Completed { id, pages }. For the last line, if let Event::Queued(title) = &queued reaches the title again.
Worked solution
enum Event {
Queued(String),
Completed { id: u32, pages: u32 },
}
fn show(event: &Event) {
match event {
Event::Queued(title) => println!("Queued: {title}"),
Event::Completed { id, pages } => println!("Completed #{id} ({pages} pages)"),
}
}
fn main() {
let queued = Event::Queued(String::from("Rust"));
let finished = Event::Completed { id: 7, pages: 120 };
show(&queued);
show(&finished);
if let Event::Queued(title) = &queued {
println!("Still have: {title}");
}
}Queued: Rust
Completed #7 (120 pages)
Still have: Rustshow borrows, so queued is intact for the last line. if let is a match with one interesting arm; it fits when you care about a single variant. Rust also checks that show covers both variants. The next lesson uses a &mut self method to move a value from one variant to another.
Completion is saved in this browser only. It does not measure mastery.