Temporary value is freed at the end of this statement

fn main() {
    let mut v1 = &mut String::new();
    v1 = &mut String::new();
    println!("{}", v1);

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;

Can anyone explain it to me?
Thanks! :grin:

1 Like

Please format your code properly so it is easy for us to read your question.

1 Like

I have opened right now an excellent way to do that:

  1. Put your code in https://play.rust-lang.org/
  2. Press RUN
  3. Look and press link '[Open a new thread in the Rust user forum]'

Look result in my post

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

but statements don't have this magic, and their scope is just that one expression:

v1 = {
   let tmp = String::new();
   let result = &mut 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.



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.