The third rule of lifetime elision says
If there are multiple input lifetime parameters, but one of them is
&self
or&mut self
because this is a method, then the lifetime ofself
is assigned to all output lifetime parameters. This makes writing methods much nicer.
Here is the tutorial describing what happened for this function
fn announce_and_return_part(&self, announcement: &str) -> &str
There are two input lifetimes, so Rust applies the first lifetime elision rule and gives both
&self
andannouncement
their own lifetimes. Then, because one of the parameters is&self
, the return type gets the lifetime of&self
, and all lifetimes have been accounted for.
We can show that all the lifetimes are not accounted for since it is possible that announcement
will have a different lifetime than &self
:
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
announcement
}
}
fn main() {
let i = ImportantExcerpt { part: "IAOJSDI" };
let test_string_lifetime;
{
let a = String::from("xyz");
test_string_lifetime = i.announce_and_return_part(a.as_str());
}
println!("{:?}", test_string_lifetime);
}
The lifetime of announcement
is not as long as &self
, so it is not correct to associate the output lifetime to &self
, shouldn't the output lifetime be associated to the longer of the input?
Why is the third rule of lifetime elision a valid way to assign output lifetime?
lifetime mismatch
between theannouncement
argument and the return type in the function prototype, explicitly noticing that you're returning data fromannouncement
. Thanks for posting this. – Hanshawannouncement
and the return type in the prototype, the function compiles, but then rust (correctly) complains about the lifetime not being long enough inmain()
. – Hanshaw