I have this if statement where both branches have to return a &HashMap<..>. In one of the branches though I have an owned HashMap and the other one I'm accessing one from a reference to some struct. Currently, I'm being forced to define an unbound let variable outside the if block to hold the owned map from the first branch (otherwise it would be freed at the end of the if block and the reference would be invalid).
struct Descriptor {
env: HashMap<String, String>
}
fn merge_env(_a: &HashMap<..>, _b: &HashMap<..>) -> HashMap<String, String> {
todo!()
}
fn example(d1: &Descriptor, d2: &Descriptor, feature_on: bool) {
// Can I somehow avoid having to declare this?
let holder;
let env = if feature_on {
holder = merge_env(&d1.env, &d2.env);
&holder
} else {
&d1.env
};
read_env(&env);
}
fn read_env(_env: &HashMap<String, String>) { todo!() }
Is there way to do this avoiding the unbound let? Maybe some wrapper that can hold both an owned and borrowed value? Also, is the current way idiomatic?