CLI and Args
Rust is one of the best languages for building command-line tools. The ecosystem is mature, binaries are small and fast, and the type system helps you handle edge cases before your users ever encounter them. In this lesson, you'll learn how to read arguments from the command line, validate input, and structure a real CLI application using the standard library.
What You'll Learn
By the end of this lesson you will write an argument parser that separates flags from positional arguments, reads the value that follows a flag, reports a bad command line as an error instead of crashing, and survives a user typing the flags in an order you did not anticipate. The trap that catches everyone is an off-by-one: a flag that consumes a value shifts every positional argument after it, and indexing by a fixed position gives a confidently wrong answer that nothing warns you about.
This is the capstone's own subject, one lesson early. The capstone's taskwork calls std::env::args() and walks it with exactly the loop you build here, and the debugging exercise below is the bug its own argument parser is seeded with. You arrive knowing how to turn a failure into a returned value rather than a panic (Error Handling) and how to work with text without indexing into it blindly (Strings and Text).
One environmental note, stated once and then relied on throughout. The Run button gives this program no arguments at all — std::env::args() yields exactly one element, the program name — so most examples here pass a written-out Vec<&str> to the parsing function instead of calling args() and hoping. The functions are the real ones; only the source of their input is simulated, and each place it happens says so.
Reading Arguments with std::env::args
Every Rust program has access to its command-line arguments through std::env::args(). This returns an iterator of String values — the first being, by convention, the program name, followed by any arguments the user passed.
fn main() {
let args: Vec<String> = std::env::args().collect();
println!("Total arguments: {}", args.len());
for (index, arg) in args.iter().enumerate() {
println!(" args[{}] = {:?}", index, arg);
}
}
In the playground above, args[0] will conventionally be the binary path — the standard library documents it as traditionally the path of the executable rather than guaranteeing it, so treat that slot as one to skip rather than a value to trust. When you run a real CLI tool like ./mytool hello world, args[1] is "hello" and args[2] is "world".
That one-slot offset is small enough to nod along to and large enough to break three separate things in the same program. The browser runner starts every program with no arguments, so the block below does what the rest of this lesson's exercises do: it hands the parsing code a simulated argument list — a Vec<&str> shaped exactly like what the shell would pass for ./report --verbose data.csv, program name and all. Work out all three printed lines before you run it.
Predict
This slice stands in for the command ./report --verbose data.csv — the same three entries std::env::args() would yield. Decide what each of the three println! lines prints, in order, before running.
fn main() {
// Stands in for the command line ./report --verbose data.csv.
// std::env::args() would yield exactly these three entries.
let args: Vec<&str> = vec!["./report", "--verbose", "data.csv"];
println!("args.len() = {}", args.len());
let first_positional = args.iter().find(|a| !a.starts_with("--"));
println!("first non-flag = {:?}", first_positional);
let file = args.get(1).copied().unwrap_or("<none>");
println!("file = {}", file);
}All three lines print something other than the obvious answer, and it is the same off-by-one each time: args.len() = 3, first non-flag = Some("./report"), file = --verbose. The program name is an ordinary element of the list — len() counts it, iterator adapters visit it, and it pushes every real argument one slot right. Skipping it is your job: args.iter().skip(1) and nothing else. The third line adds the sharper half of the lesson: even after skipping index 0, a fixed index only finds the argument you meant on a command line with no flags in front of it. Because flags and positionals interleave freely, the position of data.csv is not something an index can know — only a scan can.
Handling Missing Arguments Gracefully
A robust CLI tool never panics when arguments are missing — it falls back to defaults or prints a helpful message. The get method on slices returns an Option, making this pattern clean and safe.
fn main() {
let args: Vec<String> = std::env::args().collect();
// Use a default value when no argument is provided
let name = args.get(1).map(String::as_str).unwrap_or("World");
let times: u32 = args
.get(2)
.and_then(|s| s.parse().ok())
.unwrap_or(1);
for _ in 0..times {
println!("Hello, {}!", name);
}
}
Notice the use of .and_then(|s| s.parse().ok()) — this chains Option operations cleanly. If the argument doesn't exist or can't be parsed as a number, we fall back to 1. No unwrap panics, no verbose if let chains.
That chain is convenient, and convenience is exactly why it deserves a second look. Close the page and answer this from memory before reading on:
Recall
Without scrolling up: in Option and Result you learned what .ok() does to a Result, and in Error Handling you learned why swallowing an error is a decision rather than a convenience. In the chain args.get(2).and_then(|s| s.parse().ok()).unwrap_or(1), what happens when the user runs the tool as mytool greet three — passing the word 'three' where a count belongs — and how does that differ from passing nothing at all?
Both cases end at 1, and the program cannot tell them apart. .ok() converts Result<T, E> into Option<T> by throwing the error away, so a ParseIntError from "three" becomes the same None that a missing argument produces. For a genuinely optional value that is the right trade. For a value the user visibly tried to supply it is a silent wrong answer — they typed something, the tool ignored it, and nothing on screen admits it. When the distinction matters, keep the Result rather than flattening it, which is exactly what the build task at the end of this lesson asks you to do for --limit.
Parsing Flags and Subcommands
Many CLI tools accept flags like --verbose or subcommands like git commit. You can implement basic flag parsing by scanning arguments for known patterns.
fn main() {
let args: Vec<String> = std::env::args().collect();
let verbose = args.contains(&String::from("--verbose"));
let subcommand = args.get(1).map(String::as_str);
match subcommand {
Some("--verbose") | None => {
println!("No subcommand given. Usage: tool <command> [--verbose]");
}
Some("greet") => {
let name = args.get(2).map(String::as_str).unwrap_or("stranger");
if verbose {
println!("[DEBUG] Running greet command with name={:?}", name);
}
println!("Hey there, {}!", name);
}
Some("count") => {
let n: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(5);
if verbose {
println!("[DEBUG] Counting to {}", n);
}
for i in 1..=n {
println!("{}", i);
}
}
Some(unknown) => {
eprintln!("Unknown command: {:?}", unknown);
std::process::exit(1);
}
}
}
A few things worth noting here:
eprintln!writes to stderr, which is the correct stream for error messages.std::process::exit(1)terminates with a non-zero exit code, signalling failure to the shell.- The
--verboseflag can appear anywhere in the args list because we usecontainsrather than positional indexing.
That last point has a sting in its tail. If a flag may appear anywhere, then the positional arguments do not live at fixed indices — and code that reads args[1] and args[2] is quietly assuming the user put the flag last. The program below makes that assumption. It compiles, it runs, it exits zero, and it prints three lines that look plausible and are wrong. Commit a hypothesis about which line is wrong and why before you change anything:
Debug
This parser is given the simulated command line ./copy --verbose in.txt out.txt and should report verbose true, source in.txt, dest out.txt. It runs clean with no panic and no error — and reports the wrong source and dest. Work out what the indices actually point at before you change a line, then fix parse so a flag anywhere in the list cannot displace a positional argument.
/// A parsed command line: one flag and two positional arguments.
struct Parsed<'a> {
verbose: bool,
source: &'a str,
dest: &'a str,
}
/// args arrives exactly as the shell hands it over, program name included.
fn parse<'a>(args: &[&'a str]) -> Parsed<'a> {
// The flag may appear anywhere, so scan the whole list for it.
let verbose = args.contains(&"--verbose");
// The two positional arguments come after the program name at args[0].
let source = args.get(1).copied().unwrap_or("<missing>");
let dest = args.get(2).copied().unwrap_or("<missing>");
Parsed { verbose, source, dest }
}
fn main() {
// The browser runner passes no real arguments, so this slice stands in for
// the command ./copy --verbose in.txt out.txt.
let args: Vec<&str> = vec!["./copy", "--verbose", "in.txt", "out.txt"];
let parsed = parse(&args);
println!("verbose = {}", parsed.verbose);
println!("source = {}", parsed.source);
println!("dest = {}", parsed.dest);
}Expected output:
verbose = true source = in.txt dest = out.txt
The indices are the bug. The four entries are ./copy, --verbose, in.txt, out.txt, so args.get(1) fetches the flag and args.get(2) fetches the source — every positional argument shifted one slot right by a flag that happened to be typed first. Nothing panics, because --verbose is a perfectly ordinary &str to find at index 1; the program simply goes off to copy a file by that name. Note which line survived: verbose is right because contains scans, while source and dest are wrong because they index. The fix is to make the positionals scan as well — collect the non-flag arguments once, then take from that list by position:
fn main() {
let args: Vec<&str> = vec!["./copy", "--verbose", "in.txt", "out.txt"];
let positional: Vec<&str> = args
.iter()
.skip(1) // drop the program name
.filter(|a| !a.starts_with("--"))
.copied()
.collect();
println!("verbose = {}", args.contains(&"--verbose"));
println!("source = {}", positional.first().copied().unwrap_or("<missing>"));
println!("dest = {}", positional.get(1).copied().unwrap_or("<missing>"));
}
The .skip(1) is doing the args[0] job from the Predict above: without it the program name, which does not start with --, becomes the first positional and you have traded one off-by-one for another.
Building a Mini Calculator
Let's put everything together in a realistic example — a small calculator that takes an operation and two numbers as arguments. The browser runner passes no arguments to your program, so this example falls back to a demo argument set (add 10 3) when it is started with none; on a real terminal that fallback never triggers and you get the usage message instead.
Before you read it, decide two things for yourself, because they are what separate a toy from a tool: where should the usage message go — stdout or stderr, and why? And what exit code should the program return when the user gets the arguments wrong? Both are answered in the code below and in the paragraph after it; commit to an answer first.
// Usage goes to stderr, not stdout: a user who pipes this program's output into
// another one wants the RESULT on the pipe and the diagnostics on their terminal.
// Printing usage to stdout is how a help message ends up inside a data file.
fn print_usage() {
eprintln!("Usage: calc <add|sub|mul|div> <number> <number>");
eprintln!("Example: calc add 10 3");
}
// Takes the label as a parameter rather than building the message at the call
// site, because a parse error never names WHICH argument failed — and "is not a
// valid number" without that is a message the user cannot act on.
fn parse_number(s: &str, label: &str) -> Result<f64, String> {
s.parse::<f64>()
.map_err(|_| format!("'{}' is not a valid number for {}", s, label))
}
fn main() {
let mut args: Vec<String> = std::env::args().collect();
// The browser runner starts this program with no arguments, so fall back to
// a demo set to show the calculator working. A real CLI would drop this
// block and keep only the usage error below.
if args.len() == 1 {
println!("(no arguments given — running the demo: calc add 10 3)");
args.extend(["add", "10", "3"].map(String::from));
}
if args.len() < 4 {
print_usage();
std::process::exit(1);
}
let operation = &args[1];
let a = match parse_number(&args[2], "first argument") {
Ok(n) => n,
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
};
let b = match parse_number(&args[3], "second argument") {
Ok(n) => n,
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
};
let result = match operation.as_str() {
"add" => Ok(a + b),
"sub" => Ok(a - b),
"mul" => Ok(a * b),
"div" => {
if b == 0.0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
op => Err(format!("Unknown operation: '{}'", op)),
};
match result {
Ok(value) => println!("{} {} {} = {}", a, operation, b, value),
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
This example shows a complete CLI pattern: validate argument count early, parse each argument with a helper that returns Result, handle errors at each step, and use exit codes to communicate success or failure.
Try It Yourself
Reading about argument parsing is not the same as getting the indices right under your own name. This is a build task: a small program that reports its own pass/fail. Three functions are stubbed out, each already compiling and returning a value of the right type, so the program builds as shipped and fails on its checks rather than in the compiler. Run it as-is to see which check fails first, then implement each function until it prints All checks passed.
The checks feed in simulated argument lists rather than real ones, for the reason every exercise in this lesson has: the browser runner starts your program with no arguments, so std::env::args() would yield nothing to parse. A Vec<&str> beginning with the program name is the same shape the shell would hand you, and every trap in this lesson survives the substitution intact.
The three functions are the lesson's three ideas in order. flag_value finds a flag's value — the token after it. positional_args produces the real arguments, which means dropping args[0], dropping the flags, and dropping the token that --limit consumes. build_config assembles the result and reports problems as Err rather than panicking, keeping the distinction the Retrieval block said .ok() throws away.
Build
Finish the build. Three functions are stubbed out and the checks below them fail until each one behaves. Run it as-is to see which check fails first, decide what that function is missing, then implement all three until it prints 'All checks passed.' The checks run top to bottom, so work down from the first failure you see. Do not change the signatures or the checks.
// Three functions to finish. Each stub already compiles and returns a value of
// the right type, so the program builds as shipped and fails its CHECKS rather
// than in the compiler. Replace each placeholder body.
//
// There is no real command line here: the browser runner starts every program
// with no arguments, so the checks below feed in simulated argument lists that
// look exactly like what the shell would hand you — program name first.
#[derive(Debug, PartialEq)]
struct Config {
verbose: bool,
limit: usize,
files: Vec<String>,
}
// TODO 1: return the token that FOLLOWS name in args, or None when the flag
// is absent or is the very last token.
// flag_value(&["./r", "--limit", "3"], "--limit") -> Some("3")
// Hint: iter().position(...) finds the flag's index; get(index + 1) is the
// value, and .copied() turns Option<&&str> into Option<&str>.
fn flag_value<'a>(args: &[&'a str], name: &str) -> Option<&'a str> {
let _ = (args, name);
None
}
// TODO 2: return every POSITIONAL argument as a String — that is, everything
// except args[0] (the program name), any token starting with "--", and the
// one token that "--limit" consumes as its value.
// positional_args(&["./r", "--limit", "5", "a.csv"]) -> ["a.csv"]
// Hint: a while loop over an index lets you advance by 2 when you meet
// "--limit", which is the step a .filter() cannot express.
fn positional_args(args: &[&str]) -> Vec<String> {
let _ = args;
Vec::new()
}
// TODO 3: assemble a Config, reporting problems as Err instead of panicking.
// - no positional arguments -> Err("usage: report [--verbose] [--limit N] <file>...")
// - "--limit" present but unparseable -> Err("--limit needs a number, got '<raw>'")
// - "--limit" absent -> limit defaults to 10
// - verbose is true when "--verbose" appears ANYWHERE in the list
fn build_config(args: &[&str]) -> Result<Config, String> {
let _ = args;
Ok(Config { verbose: false, limit: 0, files: Vec::new() })
}
// --- Build checks: these must all pass. Do not edit below this line. ---
fn main() {
let full = vec!["./report", "--verbose", "--limit", "3", "a.csv", "b.csv"];
assert_eq!(
flag_value(&full, "--limit"),
Some("3"),
"flag_value should return the token AFTER the flag"
);
assert_eq!(
flag_value(&full, "--missing"),
None,
"an absent flag has no value"
);
assert_eq!(
flag_value(&["./report", "--limit"], "--limit"),
None,
"a trailing flag with nothing after it has no value"
);
assert_eq!(
positional_args(&full),
vec!["a.csv".to_string(), "b.csv".to_string()],
"positional_args must drop args[0], the flags, AND the value --limit consumes"
);
assert_eq!(
positional_args(&["./report"]),
Vec::<String>::new(),
"a bare program name has no positional arguments"
);
assert_eq!(
positional_args(&["./report", "--limit", "5"]),
Vec::<String>::new(),
"the 5 belongs to --limit, so it is not a file"
);
let config = build_config(&full).expect("the full command line should parse");
assert!(config.verbose, "--verbose anywhere in the list sets verbose");
assert_eq!(config.limit, 3, "--limit 3 should parse to 3");
assert_eq!(
config.files,
vec!["a.csv".to_string(), "b.csv".to_string()],
"only the two real file names survive into the config"
);
let defaulted = build_config(&["./report", "log.txt"]).expect("one file is enough");
assert_eq!(defaulted.limit, 10, "a missing --limit should default to 10");
assert!(!defaulted.verbose, "no --verbose means verbose stays false");
assert_eq!(
build_config(&["./report", "--verbose"]),
Err(String::from("usage: report [--verbose] [--limit N] <file>...")),
"no positional arguments is a usage error, not a panic"
);
assert_eq!(
build_config(&["./report", "--limit", "wide", "a.csv"]),
Err(String::from("--limit needs a number, got 'wide'")),
"an unparseable --limit value should be reported, not silently defaulted"
);
println!("All checks passed.");
println!("config = {:?}", config);
println!("default = limit {}", defaulted.limit);
println!("usage = {:?}", build_config(&["./report"]));
}Expected output:
All checks passed.
config = Config { verbose: true, limit: 3, files: ["a.csv", "b.csv"] }
default = limit 10
usage = Err("usage: report [--verbose] [--limit N] <file>...")Once it passes, try two variations and predict each before running:
- Start the loop at zero. In
positional_args, changelet mut index = 1;tolet mut index = 0;. Predict which check breaks before running. The fourth one does:positional_args(&full)comes back as["./report", "a.csv", "b.csv"]because the program name does not start with--and so passes the flag filter untouched. This is the Predict block's trap in your own code — index 0 is skipped by an explicit decision or it is not skipped at all. - Default the bad
--limitinstead of reporting it. Inbuild_config, replace theparse().map_err(...)?withflag_value(args, "--limit").and_then(|raw| raw.parse().ok()).unwrap_or(10). Decide which check breaks before running. The last one:build_config(&["./report", "--limit", "wide", "a.csv"])now returnsOkwithlimit: 10instead of anErr, because.ok()throws theParseIntErroraway and makes a typo indistinguishable from an absent flag. The user asked for something impossible and the tool silently did something else.
Reading a ParseIntError
This lesson has turned .parse() failures into friendly messages several times without ever looking at the error itself. It repays a look, because it is the error a CLI hits most and its variants are more informative than the one-line summary suggests.
fn main() {
for raw in ["12", "", "7.5", "-3", "9999999999999999999999", "12 "] {
match raw.parse::<usize>() {
Ok(n) => println!("{:>24} -> Ok({})", format!("{:?}", raw), n),
Err(e) => println!("{:>24} -> Err: {} | kind {:?}", format!("{:?}", raw), e, e.kind()),
}
}
}
That prints:
"12" -> Ok(12)
"" -> Err: cannot parse integer from empty string | kind Empty
"7.5" -> Err: invalid digit found in string | kind InvalidDigit
"-3" -> Err: invalid digit found in string | kind InvalidDigit
"9999999999999999999999" -> Err: number too large to fit in target type | kind PosOverflow
"12 " -> Err: invalid digit found in string | kind InvalidDigit
Read those six lines as a routine rather than a table. The message is the part to show a user, and notice its most important property: it never contains the input. invalid digit found in string does not say which string or which digit, so a CLI that prints only this leaves its user guessing. Echoing the offending value back — and the flag it came from — is your job, and it is the single biggest improvement you can make to a command-line tool's error output.
The kind is the part to branch on, and it is what turns one useless message into four actionable ones. Empty means the user gave the flag and then nothing, which is a usage error worth a different message from a typo. PosOverflow means the digits were all valid and the number simply does not fit, which is a limits problem, not a syntax one. InvalidDigit is the catch-all, and it is worth noticing what falls into it.
Three of the six lines are InvalidDigit, and the three are not the same mistake at all. "7.5" is a number the user considers perfectly reasonable — they typed a decimal into a field that wanted a whole one. "-3" is a valid integer that is invalid for this type, because the target is unsigned; parse the same string as i32 and it succeeds. And "12 " is the one that generates support tickets: it is the right number with a trailing space, invisible on the terminal, usually arriving from a shell script or a copy-paste. The error message for all three is identical. That is the argument for calling .trim() before .parse() on anything that came from a user — it costs nothing and eliminates the one failure of the three that is not the user's fault.
Unlike a compiler diagnostic, none of this comes with a -->, a highlighted span, or a help:. A runtime error tells you what went wrong and nothing about where in your program it happened, so attaching the context — which flag, which value — has to happen at the call site, while you still know.
Ordering the Argument Walk
The four lines below are the body of the walk. Here is the frame they sit inside, so args, index and out are visible rather than assumed — and note that the loop advances index at the bottom, which is what makes the continue in each branch meaningful:
fn main() {
let args = ["--limit", "5", "--json", "notes.txt", "todo.txt"];
let mut out: Vec<String> = Vec::new();
let mut index = 0usize;
while index < args.len() {
// the four shuffled lines go here
index += 1;
}
println!("files {:?}", out);
}
Arrange the code
These four lines are the body of a while loop that collects the real positional arguments, skipping the program name, the flags, and the value that --limit consumes. The index starts at 1 and the loop advances by one at the bottom. The pieces are shuffled. Put them in the order that returns just the two file names — then answer what the order is really testing: which line introduces the name the others consume, and why can the --limit test not come after the general two-dash test?
if token == "--limit" { index += 2; continue; }if token.starts_with("--") { index += 1; continue; }let token = args[index];out.push(token.to_string());
The Same Checks, Written as Tests
The build task above checks itself with assert_eq! calls inside fn main, and that is not a stylistic choice. As Testing in Rust explained, the Run button compiles and runs the file in a single command with no test mode, so anything behind #[cfg(test)] is stripped before compilation and never executes here. Any assertion that has to run must live in main.
In a Cargo project you would invert that. Here are the three parsing functions with a real test module beside them:
fn flag_value<'a>(args: &[&'a str], name: &str) -> Option<&'a str> {
let position = args.iter().position(|arg| *arg == name)?;
args.get(position + 1).copied()
}
fn positional_args(args: &[&str]) -> Vec<String> {
let mut out = Vec::new();
let mut index = 1;
while index < args.len() {
let token = args[index];
if token == "--limit" {
index += 2;
continue;
}
if token.starts_with("--") {
index += 1;
continue;
}
out.push(token.to_string());
index += 1;
}
out
}
fn parse_limit(args: &[&str]) -> Result<usize, String> {
match flag_value(args, "--limit") {
None => Ok(10),
Some(raw) => raw
.trim()
.parse::<usize>()
.map_err(|e| format!("--limit expects a whole number, got {:?}: {}", raw, e)),
}
}
fn main() {
let argv = ["./report", "--limit", "5", "a.csv", "--verbose", "b.csv"];
assert_eq!(positional_args(&argv), vec!["a.csv", "b.csv"]);
assert_eq!(parse_limit(&argv), Ok(5));
println!("All checks passed.");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positionals_survive_a_flag_that_consumes_a_value() {
let argv = ["./report", "--limit", "5", "a.csv", "--verbose", "b.csv"];
assert_eq!(positional_args(&argv), vec!["a.csv", "b.csv"]);
}
#[test]
fn the_program_name_is_never_a_positional() {
assert!(positional_args(&["./report"]).is_empty());
}
#[test]
fn a_missing_limit_flag_uses_the_default() {
assert_eq!(parse_limit(&["./report", "a.csv"]), Ok(10));
}
#[test]
fn a_limit_with_a_trailing_space_still_parses() {
assert_eq!(parse_limit(&["./report", "--limit", "5 "]), Ok(5));
}
#[test]
fn a_non_numeric_limit_is_an_error_not_a_panic() {
assert!(parse_limit(&["./report", "--limit", "soon"]).is_err());
}
}
Press Run and you get All checks passed. from main; the five tests do not run. Under cargo test the same file reports five passing tests and never calls main. Both batteries assert the same facts and differ only in which command can reach them.
The test module earns its place by naming each property in a function name. a_limit_with_a_trailing_space_still_parses is the "12 " case from the diagnostic section, pinned as a permanent regression test — and it is the reason parse_limit calls .trim() before .parse().
Transfer
Node.js exposes its command line as process.argv, an array of strings, just as Rust exposes it through std::env::args(). A developer moving between them will reach for the same indexing habits. Which statement names what genuinely transfers, rather than a surface resemblance?
Capstone milestone
Milestone — argument parsing. The capstone's taskwork reads a path and two flags from the command line, and it walks argv with the same loop you built here, advancing by two when a flag consumes a value. Confirm you can separate flags from positionals, read a flag's value, and report a bad command line as an error rather than a crash.
- Collected the real arguments by scanning rather than by indexing a fixed position
- Advanced the index by two after a flag that consumes a value, and can say what happens when you advance by one
- Skipped the program name slot, and know it is conventional rather than guaranteed
- Returned an Err for a bad or missing argument instead of panicking or exiting silently
- Turned an unusable command line into a printed message and a non-zero exit rather than a panic
Key Takeaways
std::env::args()returns an iterator — collect it into aVec<String>to work with arguments by index.args[0]is conventionally the program name — the standard library does not guarantee it, so treat it as a slot to skip rather than a value to trust; user-provided arguments start at index1.- Use
.get(n)instead of direct indexing to avoid panics when arguments are missing. - Chain
Optionmethods like.map,.and_then, and.unwrap_orfor clean, safe argument parsing. - Write errors to
stderrwitheprintln!and exit with a non-zero code usingstd::process::exit(1). - Validate argument count early and show usage instructions before attempting any parsing.
- For production CLI tools, consider the
clapcrate — it handles flags, subcommands, help generation, and shell completions automatically.
Pro Tip: Always test your CLI tool with zero arguments, one argument, and invalid types for numeric arguments. These three cases catch the vast majority of real-world user errors, and Rust's
OptionandResulttypes make handling them explicit rather than leaving them as silent panics.
Next Steps
You've built a solid CLI tool! Now it's time to put everything together in the capstone project — taskwork, a complete command-line program in four modules that reads a task file, rejects the bad lines without crashing, filters what survives, and prints the result as human text or as hand-rolled JSON.
Next lesson
Capstone Project: CLI Todo App
Build a complete command-line todo application combining structs, enums, error handling, traits, and collections
35 min