Rust Lifetimes Explained - Ensuring References Stay Valid | Rust Tutorial
Video: Rust Lifetimes Explained - Ensuring References Stay Valid | Rust Tutorial by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Lifetimes Explained - Ensuring References Stay Valid
Rust lifetimes are a core feature that guarantees references never outlive the data they point to, preventing dangling pointers and memory errors. This tutorial covers lifetime annotations, how to use multiple lifetimes in functions, and how to safely store references in structs using lifetimes.
Code
/// Returns the longest of two string slices with the same lifetime
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
/// Function with two different lifetimes, returning a reference tied to the first lifetime
fn announce_and_return<'a, 'b>(x: &'a str, y: &'b str, announcement: &str) -> &'a str {
println!("Announcement: {}", announcement);
x
}
/// Struct holding a reference with a lifetime annotation
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
/// Returns the stored string slice reference
fn get_part(&self) -> &'a str {
self.part
}
}
fn main() {
let string1 = String::from("Rust programming");
let string2 = "is awesome";
// Using longest function with lifetime annotations
let result = longest(string1.as_str(), string2);
println!("The longest string is '{}'", result);
// Using announce_and_return with different lifetimes
let announcement = "Check this out!";
let returned = announce_and_return(string1.as_str(), string2, announcement);
println!("Returned string: '{}'", returned);
// Creating a struct instance with a reference
let novel = String::from("Call me Ishmael.");
let excerpt = Excerpt { part: &novel[0..4] };
println!("Excerpt: '{}'", excerpt.get_part());
}
Key Points
- Lifetimes ensure references are valid for as long as they are used, preventing dangling pointers.
- Lifetime annotations use tick syntax (e.g., '<\'a>') to specify how long references live.
- Functions can have multiple lifetime parameters to handle references with different validities.
- Structs holding references must declare lifetimes to guarantee the data they point to lives long enough.
- Impl blocks for structs with lifetimes must also specify the lifetime parameters for methods to work safely.