error[E0716]: temporary value dropped while borrowed
--> src\main.rs:3:15
|
3 | v1 = &mut String::new();
| ^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
4 | println!("{}", v1);
| -- borrow later used here
|
help: consider using a let binding to create a longer lived value
|
3 ~ let binding = String::new();
4 ~ v1 = &mut binding;
|
let has a special magic scope when making values that are referenced. It behaves like:
let tmp = String::new();
let mut v1 = &mut tmp;
// at the end of the outer scope
drop(tmp);
but statements don't have this magic, and their scope is just that one expression:
v1 = {
let tmp = String::new();
let result = &mut tmp;
drop(tmp);
result // tmp has been freed, so result is no longer valid
};
Remember that in Rust references can't exist on their own. They're not like values held "by reference" in other languages. In Rust it's always a reference to something else that has to be stored first, and is limited by that other side's storage lifetime. let stores it for you implicitly (and in simple cases only), but other expressions in Rust generally won't.