Lifetimes in Rust are annotations that tell the compiler how long a reference must remain valid to prevent dangling pointers. They ensure that references do not outlive the data they point to, enforcing memory safety at compile time.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
In this example, the lifetime parameter 'a guarantees that the returned reference lives as long as the shorter of the two input references.