When do you need explicit lifetime annotations

Use explicit lifetime annotations when the compiler cannot infer reference validity, such as when returning a reference from an argument.

You need explicit lifetime annotations when the compiler cannot infer how long a reference lives, typically when a function returns a reference derived from one of its arguments or when multiple references with different scopes interact. Add the 'a lifetime parameter to the function signature and the references to tell the compiler that the returned reference is tied to the input reference's lifetime.

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}