A line like add Rust Patterns does two things at once if you let it: it asks for a book to be added, and it changes the queue. Keeping those as two stages makes both easier. Parsing turns text into a value that describes the request, such as Command::Add("Rust Patterns"), or into an error that says what is wrong with the text. Applying takes that value and changes program state. With the stages apart, you can test every malformed input without creating a queue, and the code that changes the queue never sees a string it has to second-guess.
The Command enum makes invalid requests impossible to represent. Add always carries a title, and List carries nothing, so no later code has to ask "did this list command have arguments?". The title is a &str borrowed from the input line, so parsing allocates nothing. The enum therefore has a lifetime parameter, Command<'a>, from Day 2: a command cannot outlive the line it was parsed from.
split_once(char::is_whitespace) splits at the first whitespace character, whether a space or a tab. Trimming the remainder then keeps spaces inside a title, such as Rust Patterns. A word-by-word method like split_whitespace would lose them.
Predict and run
Which inputs succeed? For the one that does, what does the Add variant borrow?
#[derive(Debug, PartialEq, Eq)]
enum Command<'a> {
Add(&'a str),
List,
}
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
MissingTitle,
ExtraArguments,
UnknownCommand,
}
fn parse(line: &str) -> Result<Command<'_>, ParseError> {
let line = line.trim();
let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let rest = rest.trim();
match verb {
"add" if rest.is_empty() => Err(ParseError::MissingTitle),
"add" => Ok(Command::Add(rest)),
"list" if !rest.is_empty() => Err(ParseError::ExtraArguments),
"list" => Ok(Command::List),
_ => Err(ParseError::UnknownCommand),
}
}
fn main() {
for line in ["add Rust Patterns", "list", "list now", "add"] {
println!("{:?}", parse(line));
}
}Check your prediction
Ok(Add("Rust Patterns"))
Ok(List)
Err(ExtraArguments)
Err(MissingTitle)Add borrows Rust Patterns, a slice of the original literal. add alone has no whitespace, so unwrap_or((line, "")) supplies an empty remainder, and the first guard reports MissingTitle. Try "add\tRust" with a tab after the verb, and predict the result: the tab counts as whitespace, so it parses. Then try "Add Rust" with a capital letter. Matching is exact, so it is an UnknownCommand.
Guards run in order
A match guard, the if after a pattern, adds a condition to that arm. Rust tries arms from top to bottom and takes the first one whose pattern matches and whose guard is true. That makes the order of the two list arms part of the rule. Swap them, and the plain arm catches every list first:
#[derive(Debug, PartialEq, Eq)]
enum Command {
List,
}
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
ExtraArguments,
UnknownCommand,
}
fn parse(line: &str) -> Result<Command, ParseError> {
let line = line.trim();
let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
match verb {
"list" => Ok(Command::List),
"list" if !rest.trim().is_empty() => Err(ParseError::ExtraArguments),
_ => Err(ParseError::UnknownCommand),
}
}
fn main() {
println!("{:?}", parse("list now"));
}Ok(List)The program compiles, and list now is silently accepted. The compiler does notice: it warns about an unreachable pattern on the guarded arm. Treat that warning as a bug report. Put the narrower case, the one with the guard, above the general one.
The command cannot outlive its line
Because Add borrows, the borrow checker makes sure the line stays alive while the command is in use. With the parse function from the first example, this does not compile:
fn main() {
let command;
{
let line = String::from("add Rust");
command = parse(&line);
}
println!("{command:?}");
}The error is error[E0597]: line does not live long enough, with the note that line is dropped while still borrowed. In the queue's input loop this is never a problem: each command is parsed and applied inside the same loop iteration, while its line is alive. The queue then stores an owned String copy of the title, so the book survives after the line is gone. You will trace exactly that on Day 7.
Parse into the narrowest type
Return values that already satisfy your rules: a non-empty title, a validated ID, a List with no arguments. Then the code that applies commands can trust them, and every check for malformed text lives in one function you can test on its own.
Practice
Your turn
Write parse for two commands: find TITLE and help. Find should carry the borrowed title text. An empty search returns EmptyQuery, arguments after help return ExtraArguments, and any other verb returns UnknownCommand. Assert the results for find Rust Types, find, help now and help, then print Command checks passed.
#[derive(Debug, PartialEq, Eq)]
enum Command<'a> {
Find(&'a str),
Help,
}
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
EmptyQuery,
ExtraArguments,
UnknownCommand,
}
fn main() {
// Check two valid and two invalid commands.
}Hint 1: the idea
Split the verb off once so the remainder can contain spaces, then match on the verb with a guard for each error case.
Hint 2: a first step
Trim the whole line, call split_once(char::is_whitespace).unwrap_or((line, "")), then trim the rest before matching.
Worked solution
#[derive(Debug, PartialEq, Eq)]
enum Command<'a> {
Find(&'a str),
Help,
}
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
EmptyQuery,
ExtraArguments,
UnknownCommand,
}
fn parse(line: &str) -> Result<Command<'_>, ParseError> {
let line = line.trim();
let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let rest = rest.trim();
match verb {
"find" if rest.is_empty() => Err(ParseError::EmptyQuery),
"find" => Ok(Command::Find(rest)),
"help" if !rest.is_empty() => Err(ParseError::ExtraArguments),
"help" => Ok(Command::Help),
_ => Err(ParseError::UnknownCommand),
}
}
fn main() {
assert_eq!(parse("find Rust Types"), Ok(Command::Find("Rust Types")));
assert_eq!(parse("find"), Err(ParseError::EmptyQuery));
assert_eq!(parse("help now"), Err(ParseError::ExtraArguments));
assert_eq!(parse("help"), Ok(Command::Help));
println!("Command checks passed");
}Command checks passedEach guard sits above the arm it narrows, so a malformed command is rejected before the general arm can accept it. Find("Rust Types") keeps its inner space because only the first whitespace splits. The checkpoint adds a numeric argument, which brings back the ID parser from the first lesson of today.
Completion is saved in this browser only. It does not measure mastery.