I'm working on a Rust project where I'm using the Clap library to handle command-line arguments. I have a scenario where I want to set the default_value of a command-line argument based on a value calculated at runtime, but I'm encountering a lifetime issue.
Here's a simplified example of my code:
let default_threads_name = (num_cpus::get().saturating_sub(2).max(1)).to_string();
let matches = Command::new("test")
.version("1.0")
.subcommand_required(true)
.about("uploader")
.arg(
Arg::new("threadsHash")
.long("threadsHash")
.value_name("THREADS_HASH")
.default_value(&*default_threads_name)
.help("Number of threads for hashing"),
)
.get_matches();
The get_default_threads_name function calculates a value at runtime, and I want to use this value as the default_value for the "threadsHash" argument.
However, I'm encountering a lifetime issue because the borrowed value (default_threads_name) will expire by the time get_matches() returns the value. As a result, I'm unable to use the parsed arguments effectively.
Is there a way to work around this issue and set the default_value based on a runtime-calculated value without running into lifetime problems?
Any insights or solutions would be greatly appreciated!
Just pass default_threads_name
itself and not a reference to it:
let matches = Command::new("test")
.version("1.0")
.subcommand_required(true)
.about("uploader")
.arg(
Arg::new("threadsHash")
.long("threadsHash")
.value_name("THREADS_HASH")
.default_value(default_threads_name)
.help("Number of threads for hashing"),
)
.get_matches();
You need to enable the string
feature of clap
as well.