Pass function to default (for string)
liamdawson opened this issue · comments
I'm trying to use a function called default_config()
to provide the default value for an option:
pub fn default_config() -> String {
option_env!("BIN_DEFAULT_CONFIG_PATH")
.unwrap_or("/etc/default/path")
.to_owned()
}
#[derive(Options)]
pub struct FetchOpts {
#[options(help = "Path to the config file", default = "default_config()")]
pub config: String,
}
However, that is interpreted as the literal value "default_config()"
. Passing default = default_config()
causes a syntax error panic instead.
Is there a sensible way to set that default value, taking advantage of the help text auto-generation? (If not, I can fall back to the unwrap method, which I was previously using)
I've just pushed a commit that implements this feature, with a new attribute default_expr
. The expression must be contained in a string (e.g. default_expr = "default_config()"
) because of how the Rust compiler parses item attributes.
Perfect, thank you! Will test it out soon 🙂
Can confirm, works as expected. Is the value meant to show up in the help string too, or am I confusing it with the clap
version?
A parseable default value string does show up in the usage, but the default_expr
does not. Only the Rust expression is available at compile time (the usage string is a &'static str
that is generated when derive(Options)
is expanded) and displaying that would not provide any meaningful information to the user.