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

This can be done with the action attribute. If your field is a bool then by default the action selected is ArgAction::SetTrue.

This is quite nice since you don’t need to set a value when you call the argument. It sets the value by default to true if used and false if not used when running the program.

use clap::Parser;

/// This is a simple program
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
   /// It just works!
   #[clap(long, short, action)]
   it_just_works: bool,
}

fn main() {
   let args = Args::parse();

    println!("It just works {}!", args.it_just_works)
}

To change the default behavior you can do this:

#[clap(long, short, action=ArgAction::SetFalse)]

Docs.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)