0PricingLogin
Learn Rust Coding · Lesson

Derive API

Args from structs.

The derive API

The derive API lets you describe your CLI as a struct and have clap generate the parser via #[derive(Parser)].

  • Less boilerplate than the builder API
  • Type-safe: fields become typed values

Enable it with the derive feature.

A minimal Parser struct

Annotate a struct with #[derive(Parser)] and call Cli::parse() in main. Each field is one argument.

use clap::Parser;

#[derive(Parser)]
struct Cli {
    name: String,
}

fn main() {
    let cli = Cli::parse();
    println!("Hello, {}!", cli.name);
}

All lessons in this course

  1. clap Basics
  2. Subcommands
  3. Derive API
  4. Validation and Help
← Back to Learn Rust Coding