Sub topic 9
Lifetimes in impl blocks and methods
This chapter assumes you can write structs, impl blocks, and generics. It also assumes you know the borrowing rules and the elision rules for functions. Here you will see how a struct's lifetime parameter reaches its methods, and how to pick which lifetime a method returns.
Declaring the lifetime on the impl
A struct that holds a reference has a lifetime parameter. The impl block must declare that parameter and then use it in the type name:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Attention: {announcement}");
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first = novel.split('.').next().expect("no '.' found");
let e = Excerpt { part: first };
println!("{} {}", e.level(), e.announce_and_return("hello"));
}The first 'a in impl<'a> declares the parameter, like T in impl<T>. The second 'a in Excerpt<'a> uses it. If you omit the declaration, you get error E0261 (undeclared lifetime).
If a method never needs the name, write impl Excerpt<'_> instead. The anonymous lifetime '_ means "some lifetime, I don't care which."
What elision does in methods
The third elision rule applies to methods. If one of the inputs is &self or &mut self, the lifetime of self is assigned to every elided output lifetime.
In announce_and_return, the compiler reads the signature as fn announce_and_return<'s>(&'s self, announcement: &str) -> &'s str. The output is tied to the borrow of self. It is not tied to announcement. That is usually what you want, and it is why this method compiles without annotations.
Returning the struct's own lifetime
The elided output lifetime is the borrow of self, which is often shorter than 'a. This matters when the result should outlive the struct value:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn part(&self) -> &'a str {
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let part;
{
let e = Excerpt {
part: novel.split('.').next().unwrap(),
};
part = e.part();
} // e is dropped here, but novel is still alive
println!("{part}");
}The method returns &'a str, so the result is tied to novel, not to e. If you change the return type to &str, elision ties it to &self. Then e.part() borrows e, and the program fails with E0597 (e does not live long enough).
Method-level lifetime parameters
A method can declare its own lifetimes after fn. This is useful when the result comes from an argument and not from self:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn pick<'b>(&self, other: &'b str) -> &'b str {
if other.is_empty() { "(empty)" } else { other }
}
}
fn main() {
let novel = String::from("Call me Ishmael.");
let e = Excerpt { part: &novel };
println!("{} {}", e.part, e.pick("hi"));
}Here 'b belongs only to pick. The "(empty)" literal is &'static str, which can shrink to fit 'b.
Common errors
| Error | Cause | Fix |
|---|---|---|
| E0261 | `impl Excerpt<'a>` without `impl<'a>` | Declare the lifetime on the impl |
| E0106 | Return type has a reference, but elision has no single source | Name the lifetime on the return type |
| E0597 | Result borrowed from `self` outlives the struct | Return `&'a T` instead of an elided `&T` |
Exercise
A method fn text(&self) -> &str on Excerpt<'a> returns self.part. The caller drops the Excerpt but keeps using the result, and the compiler reports E0597. What single change to the signature fixes it, and why does it work?
Show answer
Change the return type to &'a str. Elision had tied the result to the borrow of self, which ends when the Excerpt is dropped. 'a is the lifetime of the data the struct borrows, which outlives the struct, so the result stays valid.