How to Parse Command-Line Arguments with clap in Rust

Parse command-line arguments in Rust using the clap crate by defining a struct with derive macros and calling parse().

Use the clap crate to define arguments declaratively and let it handle parsing, validation, and help text automatically.

use clap::Parser;

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

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

Add clap = "4" to your Cargo.toml dependencies.