sometimes you want a variable to contain the borrowed form of a value, but in one of your branches, it needs to point to owned heap data instead. however, this owned data is generated by a function call inside the conditional, so you can't just stick &
in front of it without getting a lifetime error.
most people would probably just clone the borrowed data or factor all uses of that variable into a helper function, but you can actually use late-assigned variables for this, manually promoting the lifetime of the value to that of the outer function block.
this works because v_string
is only used in branches that initialize it, so the borrow checker can see it will never be used before being initialized.
fn main() {
let some_condition = false;
let v_string;
let v: &str;
if some_condition {
v_string = "foo".to_string();
v = &v_string;
} else {
v = "bar";
}
println!("{v}");
}