- default_value_if
- ArgPredicate
- Equals
- OsStr
Clap - set default value if other flag provided
- If log_to_file is true then log_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 the log_to_file is False would not be a problem. The code just would not use it.
examples/clap/default-value-if-equals/src/main.rs
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") }