How to Annotate Lifetimes on Functions in Rust

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.