Clap - set default value if other flag provided
-
default_value_if
-
ArgPredicate
-
Equals
-
OsStr
-
If
log_to_file
is true thenlog_file
will get a default value. -
Actually I am not sure this is such a good example for
default_value_if
as setting the default even if thelog_to_file
isFalse
would not be a problem. The code just would not use it.
use clap::builder::{ArgPredicate, OsStr}; use clap::Parser; #[derive(Debug, Parser)] struct Cli { #[arg(long)] log_to_file: bool, #[arg( long, default_value_if("log_to_file", ArgPredicate::Equals(OsStr::from("true")), "my.log") )] log_file: Option<String>, } fn main() { let args = Cli::parse(); println!("Args: {args:?}"); }
$ cargo run -q
Args: Cli { log_to_file: false, log_file: None }
$ cargo run -q -- --log-to-file
Args: Cli { log_to_file: true, log_file: Some("my.log") }
$ cargo run -q -- --log-to-file --log-file other.log
Args: Cli { log_to_file: true, log_file: Some("other.log") }
$ cargo run -q -- --log-file other.log
Args: Cli { log_to_file: false, log_file: Some("other.log") }