-
Hi, I've got a #[derive(Parser, Debug)]
struct Args {
/// Name of the person to greet
#[arg(short, long. default_value = "John")]
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
} And, for test purposes, I'd like that struct to implement impl Default for Args {
fn default -> Self {
Args { name: "John".into(), count: 1 } // <-- duplicating values that have been specified in clap
}
} Note that I want the Thank you for your help! 🙏 (I've done the search and most specific queries yield no results, OTOH searching for "default" brings many unrelated discussions but I might've overlooked something and if so: apologies in advance) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There is not a way to automatically generate this and doing so would have enough caveats (performance, only working if all fields have defaults which we shouldn't push people towards) that I don't think we should do this as a first-party thing. The performance issue stems from For test purposes, you could hack together an even slower version, assuming all fields are defaulted: use clap::Parser;
#[derive(Parser, Debug)]
struct Args {
/// Name of the person to greet
#[arg(short, long, default_value = "John")]
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
}
impl Default for Args {
fn default() -> Self {
Args::try_parse_from(&["cmd"]).expect("defaults work")
}
}
fn main() {
dbg!(Args::default());
} |
Beta Was this translation helpful? Give feedback.
There is not a way to automatically generate this and doing so would have enough caveats (performance, only working if all fields have defaults which we shouldn't push people towards) that I don't think we should do this as a first-party thing.
The performance issue stems from
default_value
. To turn those back into the field's type, we'd need to discover and run thevalue_parser
. Ideally, these wouldn't fail but could in some cases.For test purposes, you could hack together an even slower version, assuming all fields are defaulted: