Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why clap contains_id() always returns TRUE?

This is the code (I’m using clap 3.2.20):

pub fn main() {
  let m = Command::new("foo")
    .arg(
      Arg::new("bar")
        .long("bar")
        .required(false)
        .action(ArgAction::SetTrue)
      )
    .get_matches();
  if m.contains_id("bar") {
    println!("Boom!");
  }
}

It prints Boom! either I provide --bar option or not. Why and how to fix?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Per the documentation of contains_id

NOTE: This will always return true if default_value has been set. ArgMatches::value_source can be used to check if a value is present at runtime.

Now you might object that you’re not using default_value, however you’re using ArgAction::SetTrue:

When encountered, act as if "true" was encountered on the command-line

If no default_value is set, it will be false.

Emphasis mine.

So ArgAction::SetTrue implies default_value=false.

Therefore bar will always have a value, there’s no need to check whether it deoes. Just fetch the value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading