Clap: how to check if a flag was used at command line

Hi,

I'm using clap crate to parse command line for my app. I have an option with f32 value, say radius which has a default value assigned in my struct Args {} (I'm using derive clap's API).

How can I check in my code whether the --radius flag was actually specified by a user? Even if It was not explicitly used, I'd like to read the default value assigned to it.

You can specify a default value as:

#[derive(Parser)]
struct Args {
    #[clap(default_value_t = 0.0, value_parser)]
    radius: f32,
}

You can specify a field as optional (so that if the flag is not passed it is set as None)

#[derive(Parser)]
struct Args {
    #[clap(value_parser)]
    radius: Option<f32>,
}
1 Like

Thanks for your reply. The problem however is still unclear to me.
Firstly, for my following code:

#[clap(short, long, default_value_t = 100.0, value_parser)]
radius: f32,

rustc says:

error: unexpected attribute: value_parser
28 |     #[clap(short, long, default_value_t = 100.0,value_parser)]
   |                                                 ^^^^^^^^^^^^

Secondly, it's still unclear to me how to check whether the flag was used. Ideally, I'd like to do sth like:

let val = args.radius;
let was_used = args.was_used("radius");
if was_used {
    println!("{} was given", val);
} else {
    println!("using {} as the default", val);
}

I don't know about this.

You can't quite it do like that. As far as I can tell, you can either:

  • Use the default_value_t attribute to automatically put the default value when flag is not passed.
  • Leave the type as Option<f32> and then do:
if let Some(radius) = args.radius {
     println!("{} was given", radius);
} else {
     println!("using {} as default", DEFAULT_RADIUS);
}

OK, so I understand that either:

  • there might be a value predefined and looks as it was given from command line
  • or the field is an option and then I can check whether the respective flag was use or not, but I can't assign the default?

Yes.