FAQ - Help and questions

How do I fix "does not live long enough" (E0597)?

#errors#lifetimes#ownershippublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A reference was kept after the value it points to was freed at the end of its block. Move the owner to an outer scope so it lives longer than the reference, or stop using a reference and keep an owned value (a String, a clone). Never return a reference to a local variable.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Every value is freed when the block that owns it ends. A reference to it is only valid until then. E0597 says that a reference is still used after that moment, and the message marks three places: where the value is declared, where it is dropped, and where the reference is used later.

src/main.rsrust
fn main() {
    let longest: &str;
    {
        let text = String::from("a short-lived value");
        longest = &text;
    }
    println!("{longest}");
}
text
error[E0597]: `text` does not live long enough
 --> src/main.rs:5:19
  |
4 |         let text = String::from("a short-lived value");
  |             ---- binding `text` declared here
5 |         longest = &text;
  |                   ^^^^^ borrowed value does not live long enough
6 |     }
  |     - `text` dropped here while still borrowed
7 |     println!("{longest}");
  |                ------- borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.

Here text lives inside the inner braces, but longest is read after them.

How to fix it#

Choose by what the code needs:

  • Make the owner live as long as the reference: declare it in the outer scope.
src/main.rsrust
fn main() {
    let text = String::from("a value that lives long enough");
    let longest: &str = &text;
    println!("{longest}");
}
text
a value that lives long enough
  • Keep an owned value instead of a reference: let longest = text.clone(); or build a String in the first place.
  • In a function: do not return &local. Return the owned value; the caller then becomes its owner.

Common mistakes#

  • Adding lifetime annotations hoping to fix it. Annotations describe relationships, they cannot make a value live longer.
  • Storing a reference to a loop variable in a collection that outlives the loop. Push owned copies instead.
    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet