Sub topic 9
Lifetimes in impl blocks and methods
This chapter assumes you can read lifetime annotations on functions, know the three elision rules, and have written a struct that holds a reference. It covers how those pieces combine inside impl blocks. The main points are where lifetime parameters are declared, how &self changes what elision infers, and when a method must name 'a explicitly.
Declaring lifetimes on an impl block
A lifetime parameter is a generic parameter. A struct declares it after its name, and an impl block must declare it again before it can use it:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn new(part: &'a str) -> Self {
Excerpt { part }
}
fn level(&self) -> i32 {
3
}
}
fn main() {
let text = String::from("Call me Ishmael.");
let e = Excerpt::new(&text);
println!("{} {}", e.level(), e.part);
}In impl<'a> Excerpt<'a>, the first <'a> introduces the name and the second <'a> uses it. This works the same way as impl<T> Wrapper<T>. If you leave out the first one, the compiler reports E0261 (use of undeclared lifetime name 'a).
Using '_ when you do not need the name
If no method signature in the block mentions 'a, you can write the anonymous lifetime '_ instead:
use std::fmt;
struct Excerpt<'a> {
part: &'a str,
}
impl fmt::Display for Excerpt<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.part)
}
}
fn main() {
let e = Excerpt { part: "hello" };
println!("{e}");
}Writing impl fmt::Display for Excerpt with no lifetime at all is an error, E0726 (implicit elided lifetime not allowed here). The compiler wants you to show that the type has a lifetime parameter, and '_ does that without inventing a name.
What elision does to methods
The third elision rule is specific to methods. If there is a &self or &mut self parameter, every elided output lifetime is set to the lifetime of that borrow of self. This holds even when other reference parameters are present.
| Signature | Elided meaning |
|---|---|
| `fn part(&self) -> &str` | `fn part<'s>(&'s self) -> &'s str` |
| `fn pick(&self, other: &str) -> &str` | output tied to `&self`, not to `other` |
| `fn make(a: &str, b: &str) -> &str` | error `E0106`, no `self` and two inputs |
The output is tied to the borrow of self, not to 'a. These are different lifetimes. The borrow of self lasts only as long as the Excerpt value is borrowed, while 'a is how long the underlying text lives. The text always lives at least as long as the borrow of self.
Returning &'a str versus &str
The difference between the elided and the named form shows up when the result has to outlive the struct value. Compare two getters:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn part_long(&self) -> &'a str {
self.part
}
fn part_short(&self) -> &str {
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let part;
{
let e = Excerpt { part: novel.as_str() };
part = e.part_long();
}
println!("{part}");
}This compiles. part_long promises a reference valid for 'a, which is tied to novel, so the result survives after e is dropped. Now switch the call to the elided version:
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let part;
{
let e = Excerpt { part: novel.as_str() };
part = e.part_short();
}
println!("{part}");
}
// error[E0597]: `e` does not live long enoughpart_short returns a reference tied to the borrow of e. Once e is dropped at the end of the inner block, part would dangle. The body is identical in both methods. Only the signature differs, and the signature is all callers see.
Mixing self with other references
Because of rule 3, a method with extra reference parameters can surprise you:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Attention: {announcement}");
self.part
}
}The output is tied to &self. Returning announcement would fail with "lifetime may not live long enough", because the compiler cannot show that announcement lives as long as the self borrow.
If a method may return either input, name the lifetime on both:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn longer(&self, other: &'a str) -> &'a str {
if self.part.len() >= other.len() {
self.part
} else {
other
}
}
}
fn main() {
let a = String::from("short");
let b = String::from("a much longer line");
let e = Excerpt { part: a.as_str() };
println!("{}", e.longer(&b));
}Here other must live for 'a, the same lifetime as the stored text. Both branches return a &'a str, so the body type-checks.
If other should be allowed to have an unrelated lifetime, add a method-level parameter instead. It goes after the method name, and the impl block stays unchanged:
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn echo<'b>(&self, other: &'b str) -> &'b str {
other
}
}Trait implementations that produce borrowed items
A common case is an iterator that hands out slices of its source. The associated type must name 'a, because Item cannot be tied to the &mut self borrow of next:
struct Words<'a> {
rest: &'a str,
}
impl<'a> Iterator for Words<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
let trimmed = self.rest.trim_start();
if trimmed.is_empty() {
return None;
}
let end = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len());
let (word, rest) = trimmed.split_at(end);
self.rest = rest;
Some(word)
}
}
fn main() {
let text = String::from(" alpha beta gamma ");
let all: Vec<&str> = Words { rest: &text }.collect();
println!("{all:?}");
}Each word is a &'a str, so collect can keep all of them while the iterator advances. This is why Iterator::next cannot return a reference into the iterator itself. The trait signature has no way to tie Item to the &mut self borrow of each call. Types that need that are called lending iterators, and they need a different design.
Common errors in impl blocks
| Symptom | Cause | Fix |
|---|---|---|
| `E0261` undeclared lifetime `'a` | `impl Excerpt<'a>` without `impl<'a>` | Declare it: `impl<'a> Excerpt<'a>` |
| `E0726` implicit elided lifetime | `impl Excerpt { ... }` | Write `impl Excerpt<'_>` or `impl<'a> Excerpt<'a>` |
| `E0597` at a call site | Getter returns `&str` tied to `&self` | Return `&'a str` if the data is stored in `'a` |
| "lifetime may not live long enough" in a method | Returned a parameter whose lifetime is unrelated to the output | Name a shared lifetime on both |
Exercise
Given struct Config<'a> { name: &'a str }, a method fn name(&self) -> &str { self.name } compiles. A caller writes let n; { let c = Config { name: "x" }; n = c.name(); } println!("{n}"); and gets E0597. Change one thing in the signature to fix the error. Why does the fix work?
Show answer
Change the signature to fn name(&self) -> &'a str inside impl<'a> Config<'a>. With elision, the returned reference is tied to the borrow of self, so it cannot outlive c. Naming 'a says the result lives as long as the stored data (here a string literal), which is independent of c.
Exercise
Why does impl fmt::Display for Excerpt fail to compile, and what are two ways to correct it?
Show answer
Excerpt has a lifetime parameter, and an impl header may not hide it, so the compiler reports E0726. Correct it with impl fmt::Display for Excerpt<'_>, or with impl<'a> fmt::Display for Excerpt<'a>.