Command Line Arguments With clap
Define a CLI interface with clap derives so arguments are parsed, validated, and documented from one struct declaration.
Code
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(name = "convert", about = "Convert files between formats")]
struct Cli {
input: PathBuf,
#[arg(short, long, default_value_t = 1)]
level: u8,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, default_value_t = false)]
verbose: bool,
}
fn main() {
let cli = Cli::parse();
if cli.level == 0 || cli.level > 9 {
eprintln!("level must be between 1 and 9");
std::process::exit(2);
}
let output = cli.output.unwrap_or_else(|| cli.input.with_extension("out"));
if cli.verbose {
println!("input={:?} output={:?} level={}", cli.input, output, cli.level);
}
}Inside the snippet
Count the function main as the entire surface area of Command Line Arguments With clap.
Caveats
clap::Parsermust be installed first — the snippet imports it directly.
Using it
Signature: fn main()
Running the file prints labeled results such as input= — each operation’s effect is visible in the output.
Key statements
let output = cli.output.unwrap_or_else(|| cli.input.with_extension("out"));
Interactive Tools for This Topic
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.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.
FAQ
- Do I need to install anything before running this?
- Yes: `clap::Parser` 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.