One idea
match takes a value and maps each possible shape to an action. In a CLI, that value is often a command, a flag, or parsed input.
Use match when the next step depends on clear cases: add, list, done, invalid command.
Why it matters
Your CLI will receive messy input. A hostel expense tool may get add, split, total, or a typo like totla.
Instead of scattering if else checks across the file, put the decision in one match. It becomes easier to read during a hackathon demo and easier to change later.
Match a command
This example reads the first argument after the program name. Then it maps that command to an action.
You are not building the whole app here. Focus on how the branches stay explicit.
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let command = args.get(1);
match command {
Some(cmd) if cmd == "add" => println!("Add a new item"),
Some(cmd) if cmd == "list" => println!("Show all items"),
Some(cmd) if cmd == "done" => println!("Mark an item done"),
Some(other) => println!("Unknown command: {}", other),
None => println!("Usage: tasker add|list|done"),
}
}Read the match
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Prefer exact shapes
When possible, match on simple values. For command strings, you can convert Option into Option so your arms look cleaner.
This reduces guard clauses like if cmd == "add".
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let command = args.get(1).map(String::as_str);
match command {
Some("add") => println!("Add a new item"),
Some("list") => println!("Show all items"),
Some("done") => println!("Mark an item done"),
Some(other) => println!("Unknown command: {}", other),
None => println!("Usage: tasker add|list|done"),
}
}Do not skip cases
Rust match must be exhaustive. That means every possible value needs a branch.
Beginners often match only add, list, and done. The compiler then complains because it also sees missing input and unknown input. Add a fallback arm instead of fighting the compiler.
Match parsed input
A CLI often receives text and needs a number. You can match the parse result and choose what to do.
This keeps error handling close to the input that caused it.
fn handle_done(input: &str) {
match input.parse::<usize>() {
Ok(id) => println!("Mark task {} as done", id),
Err(_) => println!("Please give a number, like: tasker done 2"),
}
}
fn main() {
handle_done("2");
handle_done("two");
}Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
cargo run -- add
cargo run -- list
cargo run -- done 2
cargo run -- done two
cargo run