Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a boolean command line flag using Clap?

Tags:

rust

clap

I want to add a command line flag. It's a flag, so it does not take an argument, it is either present or not. I also need to know how to read the flag, either TRUE or FALSE.

This is the code for defining the flag:

.arg(
    Arg::with_name("metal")
        .long("metal-micky")
        .required(false)
        .help("I want metal micky"),
)

I am trying to read the value like this:

let z = matches.value_of("metal");

However it is resulting in None when I print it:

println!("FLAG: {:?}", z);

It is None even when I specify the flag on the command line.

like image 321
Peter Prographo Avatar asked Feb 28 '20 20:02

Peter Prographo


2 Answers

Don't know if this is the "approved" method but I use Args::takes_value:

.arg(
    Arg::with_name("metal")
        .long("metal-micky")
        .required(false)
        .takes_value(false)
        .help("I want metal micky"),
)

Then check if the flag was passed with matches.is_present("metal")

like image 152
yorodm Avatar answered Oct 03 '22 03:10

yorodm


This answer is outdated. What you want is:

.arg(
    Arg::with_name("metal")
        .long("metal-micky")
        .takes_value(false)
        .help("I want metal mickey")

Then you check with: matches.is_present("metal")

like image 26
Digant C Kasundra Avatar answered Oct 03 '22 05:10

Digant C Kasundra