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

Bash
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:

Rust
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: String has no attribute, so it's a positional argument, and it's required.
  • count: u8 with short, long becomes both -c and --count, and it defaults to 1.
  • loud: bool becomes 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:

Bash
cargo run -- Charles
Hello, Charles!
Bash
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

Bash
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:

Bash
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:

Rust
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*"),
    }
}
Bash
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

Bash
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. Use Option<std::path::PathBuf> for the field.
  • Add an environment variable fallback with #[arg(long, env = "GREET_NAME")] (this needs clap's env feature: 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.