Given code like
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
(The same example at playground)
This obviously fails as explained in the documentation but I have to wonder, is there some reason the compiler doesn't simply use the obvious interpretation that lifetime is minimum lifetime of all the inputs and outputs?
I'm new to Rust but it would seem obvious to me that given a signature like
fn foo(a: &t1, b: &t2, c: &t3, ...) -> &t4
it would always be safe to automatically cover everything with a single lifetime:
fn foo<'a>(a: &'a t1, b: &'a t2, c: &'a t3, ...) -> &'a t4
The compiler already suggests this in the error message. Is there some simple reason I'm failing to understand which prevents rustc
from defaulting to this and the programmer would need to declare only non-default (non-minimal) lifetimes manually if the default interpretation would require lifetimes that wouldn't be practical for the given function?