You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Lifetimes are Rust's way of ensuring that references are always valid. Smart pointers provide additional capabilities beyond regular references — like heap allocation, reference counting, and interior mutability.
Every reference in Rust has a lifetime — the scope for which the reference is valid. Most of the time, lifetimes are inferred. Sometimes you need to annotate them explicitly.
// This will not compile — r references x, but x does not live long enough
let r;
{
let x = 5;
r = &x; // ERROR: x does not live long enough
}
println!("{r}");
Lifetime annotations describe the relationship between the lifetimes of multiple references. They do not change how long values live.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
The annotation 'a says: "the returned reference will be valid for at least as long as the shorter of x and y."
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.