Build a Rust CLI With clap: Flags, Help Text and Subcommands in Ten Minutes
Ever ordered at a drive-through where the speaker only understands one exact sentence? That's a command-line tool with hand-rolled argument parsing. Build a Rust CLI with clap and get flags, --help and polite errors for free.
Ada Brackett
4 min read
Have you ever pulled up to a drive-through where the speaker only understands one exact sentence? "Number three, medium, no pickles" works. "Can I get the number three but medium and also no pickles please" gets you static and, somehow, a fish sandwich.
That's what a command-line tool with hand-rolled argument parsing feels like to use. Flags only work in one order, --help does nothing, and a typo gets you a panic message in place of a pickle-free burger.
Today we build a Rust CLI with clap, the crate most Rust command-line tools use for arguments. You describe the arguments as a struct, and clap gives you parsing, --help, --version and polite error messages. Ten minutes, no fish sandwiches.
Set up the counter
cargo new greet
cd greet
cargo add clap --features derive
The derive feature lets you describe arguments with attributes on a struct, which is the friendliest way in.
Write the menu
src/main.rs:
use clap::Parser;
/// Greets people, with optional enthusiasm.
#[derive(Parser)]
#[command(version, about)]
struct Args {
/// Who to greet
name: String,
/// How many times to say it
#[arg(short, long, default_value_t = 1)]
count: u8,
/// Shout it
#[arg(long)]
loud: bool,
}
fn main() {
let args = Args::parse();
for _ in 0..args.count {
let greeting = format!("Hello, {}!", args.name);
if args.loud {
println!("{}", greeting.to_uppercase());
} else {
println!("{greeting}");
}
}
}
Every field is an argument:
name: Stringhas no attribute, so it's a positional argument, and it's required.count: u8withshort, longbecomes both-cand--count, and it defaults to 1.loud: boolbecomes a flag. It's off unless you say--loud.
The /// doc comments aren't decoration. They become the help text. Here's documentation you can't forget to update, because it is the code.
Place your order
Everything after -- goes to your program rather than to cargo:
cargo run -- Charles
Hello, Charles!
cargo run -- Charles -c 3 --loud
HELLO, CHARLES!
HELLO, CHARLES!
HELLO, CHARLES!
Flags in any order? cargo run -- --loud Charles --count 2 works too. The drive-through finally understands full sentences.
The free stuff
cargo run -- --help
clap prints a tidy usage line, your description from the doc comment, the positional argument, every option with its short and long form, and the default for --count. You wrote zero lines of help code.
Now order something silly:
cargo run -- Charles --count 300
count is a u8, which tops out at 255, so clap refuses and tells you the value is invalid and why, instead of crashing or quietly wrapping round. Leave out the name entirely and it tells you a required argument is missing, then points you at --help. Your types are doing the validation for you.
Add a second menu: subcommands
Real tools have verbs: git commit, cargo build. In clap those are an enum:
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(version, about)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Say hello
Hello { name: String },
/// Say goodbye, dramatically
Bye {
name: String,
#[arg(long)]
tears: bool,
},
}
fn main() {
match Cli::parse().command {
Command::Hello { name } => println!("Hello, {name}!"),
Command::Bye { name, tears: false } => println!("Bye, {name}."),
Command::Bye { name, tears: true } => println!("Bye, {name}... *sobs*"),
}
}
cargo run -- bye Charles --tears
Bye, Charles... *sobs*
Each subcommand gets its own --help too: cargo run -- bye --help. Because the commands are an enum, the match has to handle every one. Add a new subcommand and forget to handle it, and the compiler tells you. It's a drive-through that physically cannot forget the fries.
Ship it
cargo build --release
./target/release/greet --help
That's a single binary with no runtime to install. Copy it anywhere that runs the same OS and CPU type.
Homework
- Add
--name-file <PATH>that reads names from a file, one per line. UseOption<std::path::PathBuf>for the field. - Add an environment variable fallback with
#[arg(long, env = "GREET_NAME")](this needs clap'senvfeature:cargo add clap --features derive,env). - The clap docs at docs.rs/clap include a derive tutorial and cookbook with many more examples.
Last week we handled errors properly. This week your tool can talk. Next time we'll teach it to loop like a pro, with iterators.
Cloud
More like this
Cloud
Build a Tiny JSON API With Axum: Rust on the Web in Fifteen Minutes
Your Rust programs have been talking to the terminal. Time they talked to the internet. Build a notes API with Axum, with routes, JSON in and out, shared state and proper 404s, in about 50 lines.
Cloud
Ollama Review: Running Local LLMs on Your Own Machine, No Cloud Required
What if your AI assistant lived in your basement instead of someone else's data centre? A review of Ollama: how to run local LLMs with it, what hardware you really need, the API that makes it useful, and where it falls short.
Cloud
Async Rust With Tokio: Build an Echo Server That Juggles a Thousand Clients
One waiter, forty tables, and nobody waits for their soup. That's async. Learn async Rust with Tokio by building a 30-line TCP echo server, then meet the one mistake that freezes the whole restaurant.