error[E0597]: borrowed value does not live long enough

I was recently writing a script, and I got the following error:

error[E0597]: borrowed value does not live long enough

Here is my code:

 fn main(){
    let mut arr = ["Hello", " ", "world!"];
    let mut res = "";
    for i in arr.iter() {
        res = format!("{}{}", res, i).as_str();
    }
}

I cannot figure out why this is erring, here is my full error:

error[E0597]: borrowed value does not live long enough
 --> test.rs:5:48
  |
5 |         res = format!("{}{}", &res, i).as_str();
  |               ------------------------         ^ temporary value dropped here while still borrowed
  |               |
  |               temporary value created here
6 |     }
7 | }
  | - temporary value needs to live until here
  |
  = note: consider using a `let` binding to increase its lifetime
  = note: this error originates in a macro outside of the current crate

Could someone please explain this?

You need to understand the difference between &str (reference to static string in memory, a lot like string literals in C) and String (heap allocated - it's yours!). This line:

let mut res = ""

Says res is of type &str - e.g. it's a reference to a static string. So format! returns a String, and you coerce it to a &str by calling as_str. But the &str you just created is a reference to a temporary variable (that only lasts for a single line). And you declared res (implicitly) to have a 'static lifetime, which is basically 'forever'.

This'll do ya:

fn main(){
    let mut arr = ["Hello", " ", "world!"];
    let mut res = "".to_owned(); //owned string - this is yours
    for i in arr.iter() {
        res = format!("{}{}", res, i); //format also returns an owned string
    }
}
2 Likes

Thanks! That seems to have done the trick, I appreciate it!