Hey, I've got a bit of a weird case & I'm having a bit of a struggle with lifetimes (nothing new...). I know exactly why it isn't working but I can't see a solution.
The end goal is a struct method that given a key, returns an enum variant that represents the value type. The value should either come from a HashMap<&'a str, Value<'a>> that comes from a struct field, or the system environment variables if present.
The problem is that the Value::String variant has to take a &'a str, and cannot take an owned string due to limitations elsewhere. env::vars() meanwhile provides key/value pairs of owned strings, which then need to be borrowed and of course don't live long enough.
Some things I've tried:
- Pre-populating the inputs with environment variables. This doesn't work because neither
knorvlive long enough.
let inputs = env::vars().map(|(k, v)| (k.as_str(), Value::String(v.as_str()))).collect::<Inputs>();
- Getting the env var inputs at the same time as other inputs. This doesn't work because the env var reference is held and subsequently dropped in the function.
fn get_input(&self, key: &'a str) -> Result<Value<'a>> {
if key.starts_with("$env_") {
let env_name = key.replace("$env_", "");
let var = env::var(env_name); // cannot return value referencing local variable
if let Ok(var) = var {
return Ok(Value::String(&var));
}
}
// snip
}
Basically, what pattern or approach or special pointer type or whatever should I be using to make sure the env vars last for 'a?
I'm happy to share more code if required. Cheers!