expression

Clap default values and optional input

A default supplies a value when the user omits an option. Option<T> instead preserves absence, which is useful when configuration precedence must be resolved later. This interface has a default limit and an optional label. Uses a fixed synthetic argument list or local data. Expected stdout (not executed): limit: 10; label set: false Common mistake: Applying a parser default when the absence of an explicit argument matters for configuration merging.

Formal Syntax & Structure

rust syntaxrust
#[arg(long, default_value_t = 10)] limit: u16

Working Example

Example Snippetrust
fn main() {    use clap::Parser;    #[derive(Parser)]    struct Cli {        #[arg(long, default_value_t = 10)] limit: u16,        #[arg(long)] label: Option<String>,    }    let cli = Cli::try_parse_from(["report"]).unwrap();    println!("limit: {}; label set: {}", cli.limit, cli.label.is_some());}
Rust Reference