Niche use of (safe) uninitialized variables

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}");
}
3 Likes

Here's a related, longer-form blog post.

(Delayed initialization; the super let proposal sketch.)

3 Likes

Oh my. New day, new madness. Who thought that bringing back the painfully-eliminated, JavaScript-esque variable hoisting would be a stellar idea?!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.