E0597 — DedSec Project
Rust E0597 — borrowed value does not live long enough The invalid lifetime A reference cannot outlive its owner. If a function tries to return a reference into a local String, that String…
Rust E0597 — borrowed value does not live long enough
The invalid lifetime
A reference cannot outlive its owner. If a function tries to return a reference into a local String, that String is destroyed on return. Lifetime annotations do not create extra storage or prolong the underlying object.
// fn broken<'a>() -> &'a str {
// let local = String::from("temporary");
// &local // invalid reference to destroyed storage
// }
fn owned() -> String {
String::from("persistent")
}
fn main() {
let text = owned();
let view: &str = &text;
assert_eq!(view, "persistent");
}
Borrow from the caller instead
If the returned slice should refer to an existing argument, make that relationship explicit:
fn first_word(input: &str) -> &str {
input.split_whitespace().next().unwrap_or("")
}
The returned &str is usable while the input remains alive. If the caller needs to keep the result after discarding the input, return an owned String instead.
Experiment
Call first_word on a long-lived String, then attempt to keep the borrowed result outside that String's scope. Read the compiler's lifetime diagnostic and change the API contract, not the annotation to a fabricated static lifetime. Repeat with a struct that must store either a borrowed view with a legitimate lifetime parameter or an owned String.
Reference: https://doc.rust-lang.org/error_codes/E0597.html
A lifetime is a relationship, not a memory allocator
For fn first_word(input: &str) -> &str, the returned value is a view inside input. Test first_word("") == "", first_word("Ada Lovelace") == "Ada" and first_word(" Alan") == "Alan". Now redesign a cache that must retain a word after the source buffer is dropped: return String with .to_owned(), rather than claiming &'static str. A literal string is static, but a slice into a caller-owned String is not. In a struct storing both a String and a reference into itself, a self-referential design requires special care; simpler ownership or stable indices are often safer than inventing lifetime parameters.