I realized that very often in Rust I need to do a following pattern:
let variable = &some_ref;
let variable = if something {
let new_variable = create_something();
&new_variable
} else {
variable
};
// Use variable here
In other words, I need to either use an existing reference or create a new owned value and use a reference to it.
But the problem is if I do it like in the example above the new_variable does not live long enough, it's dropped at the end of the first if clause.
Is there a idiomatic way to structure the code nicely to achieve the "use reference or create new and use reference to new" way? Or I just have to copy/make function for the code that uses variable 2 times - one for branch where I already have reference and another for branch where I create a owned value and that use reference to it?
Here is real-world example of how I usually use function (overlay_with_u32 in this case) to copy the behavior between 2 branches:
let source = &source;
if is_position_negative(x, y) {
let source = crop(source, x, y);
overlay_with_u32(destination, &source, x, y);
} else {
overlay_with_u32(destination, source, x, y);
};