Skip to content

How to automatically derive Default from clap annotated struct #5264

Answered by epage
wiktor-k asked this question in Q&A
Discussion options

You must be logged in to vote

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 the value_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:

use clap::Parser;

#[derive(Parser, Debug)]
struct Args {
    /// Name of the person to greet
    #[arg(short, long, default_value = "John")]
    name: String,

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by wiktor-k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants