23.12 Lifetimes
Lifetimes
Overview
Lifetimes in Rust ensure references are valid for as long as they are needed, preventing dangling references.
Topics
- Lifetime Annotations
- Borrow Checker
- Lifetime Elision
Examples
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
let string1 = String::from("long string");
let string2 = "short";
let result = longest(&string1, string2);
println!("The longest string is {}", result);