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?
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-lineIf no
default_value
is set, it will befalse
.
Emphasis mine.
So ArgAction::SetTrue
implies default_value=false
.
Therefore bar
will always have a value, there's no need to check whether it does. Just fetch the value.