I have a piece of Rust code.
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return_part<'b, 'c>(&'c self, announcement: &'b str) -> &'c str {
println!("Attention please: {}", announcement);
self.part
}
}
My question about this code is, what is the difference or connection between a and c? What does the lifetime annotation on impl represent?
'a
is the lifetime of the reference contained in the ImportantExceprt
received via self
.'b
is the lifetime of the additional string slice passed into the method.'c
is the lifetime of the reference to the object the method was called on.So 'a
and 'b
are different lifetimes of different objects, there is no connection between them.
Since self
contains a reference of lifetime 'a
but is behind a reference of lifetime 'c
, 'a
has to outlive 'c
(implicit 'a: 'c
), since shared references are covariant in their lifetime we can shorten the lifetime of the returned reference to 'c
The <'a>
on the impl simply declares a new lifetime you can use, and it's used to give the lifetime ImportantExcerpt
receives a name. Since you don't use it further you could as well remove it and use the anonymous lifetime instead:
impl ImportantExcerpt<'_> {