Sub topic 14
Structs that hold references
This chapter assumes you know how shared and mutable references work, the borrowing rules, and the basic syntax of lifetime annotations on functions (fn longest<'a>(...)). It covers what changes when a reference is stored in a struct field instead of passed through a function.
Why a struct needs a lifetime parameter
A struct that owns all its fields controls how long they live. A struct with a reference field does not control the data behind that reference. If the struct outlived that data, the field would dangle. The compiler therefore needs the struct's type to say which borrow it depends on.
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 that holds a borrow valid for 'a." The annotation does not set how long anything lives. It names a relationship the compiler checks: the Excerpt cannot be used after the borrow of text ends.
If you leave out the parameter, the compiler stops you with error[E0106]: missing lifetime specifier. Rust never guesses lifetimes in struct definitions. Lifetime elision, which works on function signatures, does not apply to field types.
What the compiler checks
The compiler treats a struct with a lifetime parameter like a borrow of the original data. While e is alive and used later, text is borrowed. These actions on text are therefore errors:
- Moving it.
- Mutating it, for example with
push_str. - Dropping it.
The usual error is E0597 ("text does not live long enough"). The compiler makes the same check here as for a plain reference. It just attaches the borrow to a struct.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let text = String::from("Call me Ishmael. Some years ago...");
e = Excerpt { part: text.split('.').next().unwrap() };
println!("{}", e.part); // fine: text is still alive here
}
// println!("{}", e.part); // uncomment: error[E0597] `text` does not live long enough
}Because borrows end at their last use, the program compiles as written. The error appears only if e is used after text is dropped.
Writing `impl` blocks
The lifetime parameter is declared after impl and then used in the type name. This is the same pattern as generics.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn len(&self) -> usize {
self.part.len()
}
// Returns data tied to the original text, not to this particular borrow of self.
fn part(&self) -> &'a str {
self.part
}
// Elision rule 3: with &self, the returned reference borrows from self.
fn announce(&self, announcement: &str) -> &str {
println!("Attention: {announcement}");
self.part
}
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let kept: &str;
{
let e = Excerpt { part: text.split('.').next().unwrap() };
kept = e.part();
println!("{}", e.len());
println!("{}", e.announce("hello"));
}
println!("{kept}");
}kept is still valid after e goes out of scope. part() returns &'a str, which is tied to text and not to e. If part() had been written as fn part(&self) -> &str, elision would tie the result to the borrow of e. The assignment to kept would then fail, because e is dropped before kept is used.
The impl<'a> is required even when no method mentions 'a. You can write impl Excerpt<'_> when you don't need to name it.
The most common gotcha: returning from `&mut self`
Elision rule 3 ties every elided output lifetime to self. For a struct that hands out slices of its input, this is almost never what you want.
struct Tokenizer<'a> {
input: &'a str,
pos: usize,
}
impl<'a> Tokenizer<'a> {
fn new(input: &'a str) -> Self {
Tokenizer { input, pos: 0 }
}
// Returning Option<&'a str> ties the word to the input, not to &mut self.
fn next_word(&mut self) -> Option<&'a str> {
let rest = &self.input[self.pos..];
let trimmed = rest.trim_start();
if trimmed.is_empty() {
return None;
}
let start = self.pos + (rest.len() - trimmed.len());
let end = trimmed
.find(char::is_whitespace)
.map_or(self.input.len(), |i| start + i);
self.pos = end;
Some(&self.input[start..end])
}
}
fn main() {
let text = String::from("one two three");
let words: Vec<&str>;
{
let mut t = Tokenizer::new(&text);
let mut found = Vec::new();
while let Some(w) = t.next_word() {
found.push(w);
}
words = found;
}
println!("{:?}", words);
}This prints ["one", "two", "three"]. With the signature fn next_word(&mut self) -> Option<&str>, each word would hold a mutable borrow of the tokenizer. The second call to next_word would then fail with E0499, and words could not outlive t. Writing &'a str states the truth: the words come from the input, not from the tokenizer's internal state.
Several lifetimes in one struct
When two references have unrelated origins, use separate parameters.
struct Match<'t, 'p> {
text: &'t str,
pattern: &'p str,
}
impl<'t, 'p> Match<'t, 'p> {
fn found_in(&self) -> Option<&'t str> {
self.text.find(self.pattern).map(|i| &self.text[i..i + self.pattern.len()])
}
}
fn main() {
let text = String::from("the quick brown fox");
let hit;
{
let pattern = String::from("quick");
let m = Match { text: &text, pattern: &pattern };
hit = m.found_in();
}
println!("{:?}", hit);
}hit outlives pattern because the result is tied only to 't. With a single shared 'a, the compiler would shrink both references to the shorter lifetime and reject this program. Use one parameter by default, and add a second only when a method needs to return one reference without tying it to the other.
Borrowed or owned fields
Storing a reference is a design decision, not a default. Use this table to choose.
| Situation | Field type | Trade-off |
|---|---|---|
| Short-lived view over data you already have, such as a parser or iterator | `&'a str` | No allocation. The struct cannot outlive the source. |
| Value must be stored, returned, or sent to another thread | `String` | Allocates. The struct is self-contained. |
| Many owners need the same data | `Rc<str>` or `Arc<str>` | Reference counting cost. No lifetime parameter. |
| Mostly borrowed, occasionally owned | `Cow<'a, str>` | More complex type. Allocates only when needed. |
A struct with a lifetime parameter spreads that parameter to everything that holds it. If Excerpt<'a> is stored in another struct, that struct needs <'a> too. Struct fields that outlive the function that created them, such as cached values or items in a long-lived collection, are usually better as owned types.
Common errors
E0106missing lifetime specifier. A field has&strwithout a lifetime. Add<'a>to the struct and write&'a str.E0597does not live long enough. The struct is used after its source was dropped. Move the source to an outer scope, or make the field owned.E0505cannot move out oftextbecause it is borrowed. A struct still holding a borrow oftextis used aftertextis moved. Reorder so the struct's last use comes first.E0499orE0502on a later call. A method returned a reference tied to&selfor&mut selfwhen it should be tied to'a. Check the signature of the method that returns the reference.E0621or "lifetime may not live long enough". A method returnsself.partwhere the signature promises a different lifetime. Align the annotations.
Exercise
A struct has the field name: &'a str and the method fn name(&self) -> &str { self.name }. Why might a caller be unable to keep the returned name after the struct is dropped, and how do you fix it?
Show answer
With elision rule 3, the returned reference is tied to the borrow of &self, so it cannot outlive the struct. The data actually lives for 'a. Change the signature to fn name(&self) -> &'a str so the result is tied to the original source instead.
Exercise
Rewrite struct Config { path: &str } so it compiles, and then say what you would change if Config must be returned from a function that builds the path with format!.
Show answer
Write struct Config<'a> { path: &'a str }. A path built with format! is a temporary String owned by the function, so a Config holding a borrow of it cannot be returned (E0515 or E0597). Change the field to path: String so Config owns its data.