Derive API
Args from structs.
Derive API is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}Field becomes positional
A bare field like name: String is a required positional argument. The field name becomes its value name.
use clap::Parser;
#[derive(Parser)]
struct Cli {
input: String,
output: String,
}Optional fields
Wrap a field in Option to make it optional. If the user omits it, you get None.
use clap::Parser;
#[derive(Parser)]
struct Cli {
#[arg(short, long)]
config: Option<String>,
}Flags and short/long
The #[arg(short, long)] attribute derives -v and --verbose from the field name. A bool field becomes a switch.
use clap::Parser;
#[derive(Parser)]
struct Cli {
#[arg(short, long)]
verbose: bool,
}Typed values
clap parses into the field's type. A u32 field rejects non-numeric input automatically.
use clap::Parser;
#[derive(Parser)]
struct Cli {
#[arg(short, long, default_value_t = 1)]
count: u32,
}Modeling a parsed Cli
Once parsed, a Cli struct is plain data. This runnable version shows how you would use the fields after parsing.
struct Cli {
name: String,
count: u32,
verbose: bool,
}
fn main() {
let cli = Cli { name: "Alice".to_string(), count: 2, verbose: true };
for _ in 0..cli.count {
println!("Hello, {}! (verbose={})", cli.name, cli.verbose);
}
}Subcommands as enums
With the derive API, a #[derive(Subcommand)] enum models subcommands. Each variant is a command.
use clap::{Parser, Subcommand};
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
cmd: Commands,
}
#[derive(Subcommand)]
enum Commands {
Add { task: String },
List,
}Matching enum subcommands
After Cli::parse(), match the enum to dispatch. Variant data destructures cleanly.
use clap::Parser;
fn run(cli: Cli) {
match cli.cmd {
Commands::Add { task } => println!("add {}", task),
Commands::List => println!("list"),
}
}Metadata via command attribute
Put #[command(name, version, about)] on the struct to set CLI metadata. version can read from Cargo automatically.
use clap::Parser;
#[derive(Parser)]
#[command(name = "greet", version, about = "Greets people")]
struct Cli {
name: String,
}Demonstrating enum dispatch
The match-on-enum pattern is the heart of derive subcommands. Here is the same idea in self-contained Rust.
enum Command {
Add(String),
List,
}
fn main() {
let cmd = Command::Add("Write code".to_string());
match cmd {
Command::Add(task) => println!("Added: {}", task),
Command::List => println!("Listing"),
}
}Quick Check
Test your understanding of the derive API.
Recap
The derive API turns structs into parsers:
#[derive(Parser)]plusCli::parse()- Bare fields are positionals;
Optionmakes them optional #[arg(short, long)]derives flags and options#[derive(Subcommand)]enums model subcommands
Next: validation and polished help output.
Frequently asked questions
Is the “Derive API” lesson free?
Yes — the full text of “Derive API” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Derive API”?
Args from structs. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Derive API” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.