Add a lifetime parameter like 'a to the function signature and apply it to input and output references to ensure the returned reference is valid.
Annotate lifetimes on functions by adding a lifetime parameter (e.g., 'a) to the function signature and applying it to all reference arguments and return types that need to live for that duration.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
This tells the compiler that the returned reference will live as long as the shortest-lived of the two input references.
Lifetimes tell the compiler how long a reference is valid so it can ensure you don't use data that has been deleted. Think of it like a lease agreement: you are promising that the data you are borrowing will exist for at least as long as the function needs it. You use this whenever a function takes references as input and returns a reference as output.