Parser Capstone
Command Parser
Convert Text into an Enum
A parser can turn raw command text into an enum so later code handles typed cases instead of strings.
Program
Play the program to choose a command string and route the parsed enum.
command_enum_parser.rs
enum Command {
Add(String),
Done(String),
Unknown,
}
fn main() {
let input = ;
let command = parse_command(input);
let message = describe(command);
println!("{message}");
}
fn parse_command(input: &str) -> Command {
match input.split_once(':') {
Some(("add", value)) => Command::Add(value.to_string()),
Some(("done", value)) => Command::Done(value.to_string()),
_ => Command::Unknown,
}
}
fn describe(command: Command) -> String {
match command {
Command::Add(value) => format!("add:{value}"),
Command::Done(value) => format!("done:{value}"),
Command::Unknown => "unknown".to_string(),
}
}
enum Command {
Add(String),
Done(String),
Unknown,
}
fn main() {
let input = ;
let command = parse_command(input);
let message = describe(command);
println!("{message}");
}
fn parse_command(input: &str) -> Command {
match input.split_once(':') {
Some(("add", value)) => Command::Add(value.to_string()),
Some(("done", value)) => Command::Done(value.to_string()),
_ => Command::Unknown,
}
}
fn describe(command: Command) -> String {
match command {
Command::Add(value) => format!("add:{value}"),
Command::Done(value) => format!("done:{value}"),
Command::Unknown => "unknown".to_string(),
}
}
enum Command {
Add(String),
Done(String),
Unknown,
}
fn main() {
let input = ;
let command = parse_command(input);
let message = describe(command);
println!("{message}");
}
fn parse_command(input: &str) -> Command {
match input.split_once(':') {
Some(("add", value)) => Command::Add(value.to_string()),
Some(("done", value)) => Command::Done(value.to_string()),
_ => Command::Unknown,
}
}
fn describe(command: Command) -> String {
match command {
Command::Add(value) => format!("add:{value}"),
Command::Done(value) => format!("done:{value}"),
Command::Unknown => "unknown".to_string(),
}
}
enum parser
`parse_command` converts raw text into a typed `Command` value.
payload
`Add` and `Done` carry the parsed task name as owned `String` data.
routing
`describe` matches the enum instead of reparsing the original string.