Lifetimes and Ownership Revisited
Lifetimes prevent dangling references and ensure memory safety.
Why Lifetimes?
To ensure references are valid as long as needed.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Here, 'a
is a lifetime parameter stating both inputs and output share the same lifetime.
Rust usually infers lifetimes, but in complex cases, you specify them explicitly.