Sub topic 10
Structs That Hold References
This chapter assumes you know how shared and mutable references work, the rule that a value has many readers or one writer, and how lifetime annotations on functions work. It covers what changes when a reference is stored in a struct field instead of passed as an argument.
Why a struct would hold a reference
Most structs own their data. A String field owns its heap buffer and frees it when the struct is dropped. Sometimes you want a struct that points into data owned elsewhere. Examples are a parser that walks over an input string, a view over a configuration file, or a result that names the slice it matched. Copying the data would waste memory, so the struct stores a reference.
The compiler then needs to know one thing: how long the referenced data lives compared with the struct. A struct that outlives its data would hold a dangling reference. So the struct must declare a lifetime parameter, and the compiler checks every use against it.
Declaring the lifetime parameter
Lifetime elision does not apply to struct fields. You must always name the lifetime.
struct Excerpt {
part: &str,
}
fn main() {
let e = Excerpt { part: "hello" };
println!("{}", e.part);
}This does not compile. The compiler reports E0106, "missing lifetime specifier", and points at &str. The fix is to declare a parameter in angle brackets and use it on the reference.
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);
}Read Excerpt<'a> as: "an Excerpt cannot outlive the region 'a, and part is valid for all of 'a." The name 'a is a convention. Any identifier after the apostrophe works.
The lifetime is part of the type. Excerpt<'a> is a different type from a plain Excerpt, and you cannot leave the parameter out when you write the type in a function signature or an impl header. Outside a signature, such as in let e = Excerpt { ... }, inference fills it in.
What the compiler enforces
The compiler picks 'a for each value. It chooses a region that is no longer than the data lives and at least as long as the struct is used. If no such region exists, you get an error.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let text = String::from("one. two");
e = Excerpt { part: text.split('.').next().unwrap() };
}
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 is used afterward. Moving the println! inside the inner block, or moving text out to the outer scope, fixes it.
Writing `impl` blocks
The lifetime parameter is declared after impl and then used on the type, exactly as with generics.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn new(part: &'a str) -> Self {
Excerpt { part }
}
fn len(&self) -> usize {
self.part.len()
}
fn announce(&self, msg: &str) -> &str {
println!("Attention: {msg}");
self.part
}
}
fn main() {
let text = String::from("Call me Ishmael.");
let e = Excerpt::new(&text);
println!("{} {}", e.len(), e.announce("news"));
}Note three points:
impl<'a> Excerpt<'a>repeats'atwice. The first is a declaration and the second is a use.lenneeds no annotation, because it returns no reference.announcereturns&strwith no annotation. The third elision rule applies: when a method takes&self, every elided output lifetime is the lifetime of&self. The result is therefore tied to the borrow of theExcerptitself, not tomsg.
Returning data that outlives the struct borrow
The third elision rule is not always what you want. It makes the returned reference live no longer than the borrow of the struct, even when the data underneath lives longer. The next example shows where this matters.
struct Parser<'a> {
input: &'a str,
pos: usize,
}
impl<'a> Parser<'a> {
fn new(input: &'a str) -> Self {
Parser { input, pos: 0 }
}
fn next_word(&mut self) -> Option<&'a str> {
let input = self.input;
let rest = &input[self.pos..];
let trimmed = rest.trim_start();
if trimmed.is_empty() {
self.pos = input.len();
return None;
}
let start = self.pos + (rest.len() - trimmed.len());
let end = trimmed
.find(char::is_whitespace)
.map_or(input.len(), |i| start + i);
self.pos = end;
Some(&input[start..end])
}
}
fn main() {
let text = String::from(" the quick brown fox ");
let mut p = Parser::new(&text);
let first = p.next_word();
let second = p.next_word();
println!("{:?} {:?}", first, second);
}This prints Some("the") Some("quick").
The return type is Option<&'a str>, not Option<&str>. The words are slices of the original text, not of the parser. Annotating 'a says so. The caller can then keep first while calling next_word again.
If you wrote -> Option<&str>, elision would tie the result to &mut self. Holding first would keep the parser mutably borrowed, and the second call would fail with E0499, "cannot borrow p as mutable more than once at a time". This is a common error with parser and iterator types. When a method hands out pieces of the underlying data, return &'a T, not an elided reference.
Copying the reference out
Notice the line let input = self.input; in next_word. A shared reference is Copy, so this copies the pointer and keeps the full lifetime 'a. Slicing through self would also work here, but copying out makes the intent explicit, and it avoids borrow conflicts when you later mutate self.pos.
Mutable references as fields
A struct can hold &'a mut T. The struct then has exclusive access to the target for as long as the struct is in use.
struct Tally<'a> {
total: &'a mut u32,
}
impl<'a> Tally<'a> {
fn add(&mut self, n: u32) {
*self.total += n;
}
}
fn main() {
let mut sum = 0;
{
let mut t = Tally { total: &mut sum };
t.add(2);
t.add(3);
}
println!("{sum}");
}This prints 5. While t is alive, reading sum directly would be an error, because the mutable borrow is still active. Mutable references are not Copy, so you cannot duplicate the field out as in the parser example.
Several lifetimes
One parameter is enough when all references in a struct share a region. Use more than one when the references come from unrelated sources and callers need them kept apart.
struct Highlight<'t, 'l> {
text: &'t str,
label: &'l str,
}
impl<'t, 'l> Highlight<'t, 'l> {
fn text(&self) -> &'t str {
self.text
}
}
fn main() {
let doc = String::from("borrowing is useful");
let word = {
let label = String::from("keyword");
let h = Highlight { text: &doc[..9], label: &label };
println!("{}", h.label);
h.text()
};
println!("{word}");
}The label is dropped at the end of the block, but word still points into doc. With a single shared 'a on both fields, the compiler would pick the shorter region for both, and this code would fail. Start with one lifetime. Split it only when a real call site needs the separation.
Borrowed field or owned field
| Choice | Field type | Good when | Cost |
|---|---|---|---|
| Borrow | `&'a str` | The struct is short-lived and the data clearly outlives it | Lifetime parameter spreads to every type that contains the struct |
| Own | `String` | The struct must be stored, returned, or sent to another thread | One allocation and a copy |
| Share | `Rc<str>` or `Arc<str>` | Many owners need the same data | Reference counting |
A struct with a lifetime parameter is hard to put in a long-lived place, such as a field of a larger struct that outlives the data, or the return value of a function that created the data. If the lifetime annotations keep spreading through your code, store an owned type instead. This is a design choice, not a failure. A 'static bound on a field, such as &'static str, is fine for string literals but does not accept borrowed String data.
Common errors
- E0106, missing lifetime specifier. A field has
&Twith no lifetime. Add<'a>to the struct and'ato the reference. - E0726, implicit elided lifetime not allowed here. You wrote
impl Excerptwithout the parameter. Writeimpl<'a> Excerpt<'a>, orimpl Excerpt<'_>if you do not need to name it. - E0597, does not live long enough. The struct is used after the borrowed value is dropped. Extend the owner's scope or shorten the struct's use.
- E0499 or E0502 after a method call. A method returned an elided reference tied to
&selfor&mut self. Return&'a Tif the data really outlives the struct.
Exercise
In impl<'a> Parser<'a> { fn rest(&self) -> &str { &self.input[self.pos..] } }, what lifetime does the returned &str have, and how do you let a caller keep the result after the parser is gone?
Show answer
Under elision rule 3 the result gets the lifetime of the &self borrow, so it cannot outlive the borrow of the parser. Change the signature to fn rest(&self) -> &'a str. The slice then borrows from the original input, which lives for 'a, and the caller may keep it after the parser is dropped.
Exercise
Why does this fail, and what is the smallest fix? struct Config { name: &str }
Show answer
Struct fields need an explicit lifetime, and elision does not apply to them, so the compiler reports E0106. Declare a parameter and use it: struct Config<'a> { name: &'a str }. If the struct must outlive its source, change the field to String instead.