Rust CLI Tool with Clap
Build a command-line tool in Rust using Clap with derive macros for subcommands, typed arguments, environment variable fallback, colored output, and shell.
Code
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = "mycli", version = "1.0")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Build { input: String, #[arg(short, long, default_value = "dist")] output: String },
Deploy { #[arg(long)] verbose: bool },
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Build { input, output } => println!("Building {input} → {output}"),
Commands::Deploy { verbose } => println!("Deploying (verbose: {verbose})"),
}
}How it works
Count the function main as the entire surface area of Rust CLI Tool with Clap.
Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Caveats
clap::must be installed first — the snippet imports it directly.
Putting it to use
The demo output is labeled (Building, Deploying (verbose:), so every printed line maps back to its originating operation.
Core lines
match cli.command {
Commands::Build { input, output } => println!("Building {input} → {output}"),
Commands::Deploy { verbose } => println!("Deploying (verbose: {verbose})"),
}
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Yes: `clap::` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.