Clap CLI Argument Parsing
Parse CLI arguments with clap derive macros for type-safe command-line tools.
Code
use clap::Parser;
#[derive(Parser, Debug)]
#[command(name = "app", version, about)]
struct Args {
#[arg(short, long, default_value = "8080")]
port: u16,
#[arg(long, default_value = "localhost")]
host: String,
#[arg(long)]
verbose: bool,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(clap::Subcommand, Debug)]
enum Command {
Serve,
Build { output: String },
}
fn main() {
let args = Args::parse();
println!("{:?}", args);
}What the code does
Clap CLI Argument Parsing is built around the function main.
What to watch for
- Plan for an install step:
clap::Parseris a real dependency, resolved by the package manager.
Applying it
Entry signature: fn main()
Statements that matter
let args = Args::parse();
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
- What does this need from the package registry?
- These are real dependencies: `clap::Parser`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.