Command Line Arguments With clap

Define a CLI interface with clap derives so arguments are parsed, validated, and documented from one struct declaration.

RustCli Tooling

Code

rustsnippet
29 lines
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::Parser must 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

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.