How to parse command line arguments with clap

Use the clap crate with the derive feature to declaratively define and parse command-line arguments in Rust.

Use the clap crate to define arguments declaratively and parse them automatically. Add clap to Cargo.toml, define a struct with #[derive(Parser)], and call parse() in main.

use clap::Parser;

#[derive(Parser, Debug)]
#[command(name = "myapp")]
struct Args {
    /// The query string to search for
    query: String,
    /// The path to the file to search in
    file_path: String,
}

fn main() {
    let args = Args::parse();
    println!("Searching for {} in {}", args.query, args.file_path);
}

Add this to Cargo.toml:

[dependencies]
clap = { version = "4", features = ["derive"] }