Lifetimes – Rust
Why references need lifetime annotations and how to read them.
Every reference has a lifetime: the region of code in which it is valid. Most of the time the compiler infers it. When it cannot decide how input and output references relate to each other, you have to tell it with annotations like 'a.
fn laengerer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let x = String::from("long enough");
let ergebnis;
{
let y = String::from("short");
ergebnis = laengerer(&x, &y);
println!("{ergebnis}"); // ok: y is still alive
}
// println!("{ergebnis}"); // error: y does not live long enough
}The annotation 'a does not change any lifetime; it describes a relationship: the result is valid at most as long as the shorter-lived of the two inputs. This is how Rust prevents “dangling references”:
// fn kaputt() -> &String { // error: missing lifetime specifier
// let s = String::from("x");
// &s // s is freed at the end of the function!
// }
fn richtig() -> String {
let s = String::from("x");
s // return ownership instead of a reference
}Structs that hold references need lifetime parameters. The struct then must never outlive the borrowed text.
struct Auszug<'a> {
text: &'a str,
}
impl<'a> Auszug<'a> {
fn erster_satz(&self) -> &str {
self.text.split('.').next().unwrap_or("")
}
}
fn main() {
let roman = String::from("Once upon a time. And then a lot happened.");
let a = Auszug { text: &roman };
println!("{}", a.erster_satz()); // Once upon a time
}In most functions you do not have to write lifetimes at all, thanks to the elision rules: if a function has exactly one reference parameter, the output gets the same lifetime. For methods with &self, the output gets the lifetime of self. The lifetime 'static applies to the entire program (e.g. string literals).
String instead of &str), clone once, or store indices instead of references. Long lifetime signatures are often a sign that a design based on ownership would be simpler.'static as a bound (T: 'static) does not mean “lives forever” but “contains no short-lived references”. A String satisfies it even though it is freed earlier.