Sub topic 10
Structs That Hold References
Prerequisites
This chapter assumes you can write functions that take &T and &mut T. It also assumes you know the rule "many readers or one writer" and have seen 'a lifetime annotations on functions.
Why the struct needs a lifetime parameter
A struct that stores a reference does not own the data behind it. The compiler must make sure the struct never outlives that data. A lifetime parameter gives that relationship a name.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let first = text.split('.').next().unwrap();
let e = Excerpt { part: first };
println!("{}", e.part);
}Excerpt<'a> means: "an Excerpt cannot live longer than the text that part points into." Here text lives to the end of main, and e is used before that, so the code compiles.
Unlike function signatures, struct definitions never get lifetimes through elision. You must always write 'a on the struct and on every field reference.
What the compiler rejects
If the owner is dropped while the struct is still in use, the borrow checker reports an error.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let text = String::from("short lived");
e = Excerpt { part: &text };
}
println!("{}", e.part);
}This does not compile. The error is E0597: text does not live long enough. text is dropped at the closing brace of the inner block, but e.part is used after it.
Methods on a struct with a lifetime
Write the parameter after impl and again in the type name: impl<'a> Excerpt<'a>. Inside the block you choose which lifetime each returned reference carries.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn len(&self) -> usize {
self.part.len()
}
fn part(&self) -> &'a str {
self.part
}
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let kept;
{
let e = Excerpt {
part: text.split('.').next().unwrap(),
};
println!("{}", e.len());
kept = e.part();
}
println!("{kept}");
}part returns &'a str, so the result is tied to text, not to the borrow of e. That is why kept is still valid after e goes out of scope. If you wrote fn part(&self) -> &str, elision would tie the result to &self. The program would then fail to compile, because e is dropped before kept is used.
| Return type in a method | Lifetime the result gets | Result can outlive the struct? |
|---|---|---|
| `&str` (elided) | The `&self` borrow | No |
| `&'a str` | The data the struct borrows | Yes |
Common errors
- "missing lifetime specifier": you wrote
part: &strin a struct. Add<'a>to the struct and&'a strto the field. - "
xdoes not live long enough": the owner is dropped before the last use of the struct. Move the owner to an outer scope, or make the struct own its data. - Annotating
impl Excerptwithout<'a>: the compiler reports an elided or missing lifetime in the type path. Writeimpl<'a> Excerpt<'a>, orimpl Excerpt<'_>if you never name the lifetime.
Exercise
In the Excerpt impl block, what changes for callers if fn part(&self) -> &'a str is rewritten as fn part(&self) -> &str?
Show answer
Elision gives the returned reference the lifetime of the &self borrow instead of 'a. The result can then no longer outlive the Excerpt value. A caller that keeps the result after the Excerpt is dropped, such as kept above, gets a borrow checker error.
Exercise
Why does the compiler require Excerpt<'a> to declare a lifetime, when fn first_word(s: &str) -> &str does not?
Show answer
Elision applies only to function signatures. A struct definition has no input reference to infer from, so the lifetime must be named so the compiler can check that the struct does not outlive the data it borrows.