The Rust book provides the following code to illustrate a valid function definition where explicit lifetimes are required:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Later in that section, the authors introduce the rules of lifetime elision. The second rule of lifetime elision states that
if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters.
According this rule, the following function definition should be valid as well:
fn longest<'a>(x: &'a str, y: &'a str) -> &str { // No explicit return lifetime
// snip
}
Since longest
has only one input lifetime parameter, the output lifetime parameter should be inferred as 'a
. But this code fails to compile. The borrow checker provides the following help message:
help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments.
What does this mean and why can't the inferred lifetime be used in this case?