From the Rust programming language book I reached the chapter of lifetimes. I can't understand why is it so hard for the Rust compiler to automatically give the function arguments the shortest lifetime of the parameters passed.
Example:
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
}
}
Rust will complain about lifetime annotations and I would have to write the following:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {...}
This will result in giving the shortest lifetime. If Rust could automatically know the shortest lifetime and assign it to 'a
then why would I annotate the function signature manually?
In other words why doesn't the Rust compiler just choose the shortest lifetime by just looking at the parameters passed string1
and string2
and assign the shortest lifetime to 'a
?
P.S. I'm assuming that you will always have equal lifetimes (like this example) or one indented in another, in which case you would want the shortest lifetime to avoid dangling references.