Consider the following example from the Book:
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<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
It is said that (emphasis mine)
The function signature now tells Rust that for some lifetime
'a
, the function takes two parameters, both of which are string slices that live at least as long as lifetime'a
. The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime'a
. In practice, it means that the lifetime of the reference returned by thelongest
function is the same as the smaller of the lifetimes of the references passed in. These constraints are what we want Rust to enforce.
Shouldn't the bolded sentence be The function signature also tells Rust that the string slice returned from the function will live at most as long as lifetime 'a
.? That way, we are assured that as long as both x
and y
are alive, then the return value would also be valid, because the latter references the former.
To paraphrase, if x
, y
and the return value all live at least as long as lifetime 'a
, then the compiler can simply let 'a
be an empty scope (which any item can outlive) to satisfy the restriction, rendering the annotation useless. This doesn't make sense, right?
x
andy
. – nalzokx
andy
are still valid. – Jmbfor all 'a, 'a≤'x and 'a≤'y implies 'a≤'r
(with'x
,'y
and'r
the lifetimes ofx
,y
, and the return value respectively). For that relation to hold for all'a
, then you must necessarily have'x≤'r
or'y≤'r
– Jmb