In Rust, when a function has multiple reference parameters, explicit lifetime annotations are required if the return type is a reference. I understand that Rust uses lifetime elision rules in simple cases, but when there are multiple lifetimes, why doesn’t Rust automatically infer the shortest one?
For example, in this function:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
Why does Rust require the explicit 'a annotation instead of assuming the shortest lifetime by default? Wouldn’t choosing the shortest lifetime always be the safest approach?
In contrast, this function compiles without explicit lifetimes:
fn example(x: &str) -> &str {
x // ✅ This compiles! Rust infers the same lifetime.
}
Why does Rust allow lifetime elision in example but not in longest? I'd love to understand the reasoning behind this.
But I'm afraid I don't know your mental model of lifetimes, or how you wish elision did act, well enough to make this comment constructive or elucidating.