Sub topic 8
Structs that borrow data
This chapter assumes you know ownership and moves, shared and mutable references, String versus &str, and the basics of generics and impl blocks. It also assumes you have seen the 'a syntax on functions. Here you will apply it to struct definitions.
Why a struct needs a lifetime parameter
A struct that owns its data, such as one with a String field, controls how long that data lives. A struct with a reference field does not. The data lives somewhere else, and the compiler must know that the struct cannot outlive it. Otherwise the struct would hold a dangling reference.
For functions, elision can often fill in the lifetime. For struct fields it never does. You must name the lifetime:
struct Config {
name: &str,
}
// error[E0106]: missing lifetime specifierThe fix is to declare a lifetime parameter on the struct and use it in the field type:
struct Excerpt<'a> {
part: &'a str,
}
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.part);
}Excerpt<'a> reads as: "an Excerpt that holds a &str valid for at least 'a." The 'a is generic, like a type parameter. Each Excerpt value gets its own concrete 'a, chosen by the compiler from the borrow that fills part.
What the annotation promises
The parameter creates one rule. An Excerpt<'a> value cannot be used after the data behind 'a is gone. The compiler enforces this at every use of the struct, not only where it is created.
Here is the same struct used incorrectly:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let novel = String::from("Call me Ishmael. Some years ago...");
e = Excerpt { part: novel.split('.').next().unwrap() };
} // novel is dropped here
println!("{}", e.part);
}
// error[E0597]: `novel` does not live long enoughThe struct itself is fine. The error appears because e is used after novel is dropped. The compiler points at the borrow of novel, not at the struct definition.
Fields with several references
A struct may have many reference fields. You have two choices.
One shared parameter is the common case:
struct Span<'a> {
source: &'a str,
label: &'a str,
}Both fields use 'a. For any one value, 'a becomes the region where both borrows are valid, which is their overlap. The struct is usable only inside that overlap.
Separate parameters let the fields have unrelated lifetimes:
struct Pair<'a, 'b> {
left: &'a str,
right: &'b str,
}
fn main() {
let left = String::from("outer");
let shown;
{
let right = String::from("inner");
let pair = Pair { left: &left, right: &right };
shown = pair.left;
}
println!("{shown}");
}This compiles because pair.left has type &'a str, and 'a does not depend on right. If you change the struct to Pair<'a> with both fields &'a str, the same main fails with E0597 on right. With one parameter, shown would have to stay valid as long as right is.
Start with one parameter. Add a second only when a caller needs to take one field out and keep it longer than the other borrow, as main does above.
Returning data that outlives the struct
A struct that walks through borrowed text is a typical use. This example also shows a distinction that matters in practice. Methods are covered fully in the next chapter. Here, look at the return type:
struct Words<'a> {
rest: &'a str,
}
impl<'a> Words<'a> {
fn new(text: &'a str) -> Self {
Words { rest: text }
}
fn next_word(&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(" borrow checker rules ");
let mut words = Words::new(&text);
let first = words.next_word().unwrap();
let second = words.next_word().unwrap();
println!("{first} {second}");
}The return type is Option<&'a str>, not Option<&str>. With the elided form, the output lifetime would be tied to &mut self. Then first would keep words mutably borrowed, and the second call to next_word would fail with E0499. Writing 'a says that the returned slice borrows from text, not from the Words value. The Words value can then keep changing while earlier results stay valid.
Elided lifetimes in struct types
When you write a function that returns a borrowing struct, you may omit the name but not the fact that a lifetime exists. Use '_ to say "the inferred lifetime":
struct Excerpt<'a> {
part: &'a str,
}
fn excerpt_of(text: &str) -> Excerpt<'_> {
Excerpt { part: text.split('.').next().unwrap_or(text) }
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let e = excerpt_of(&novel);
println!("{}", e.part);
}Elision gives the single input lifetime to '_ in the output. Writing plain Excerpt without <'_> is allowed in signatures, but it hides the borrow from readers. Prefer Excerpt<'_>.
Other forms a borrowing struct can take
- Mutable references.
struct Counter<'a> { count: &'a mut u32 }works the same way. While the struct exists, the target is exclusively borrowed, so nothing else can read or write it. - Wrapped references.
Option<&'a T>,Vec<&'a str>, and&'a [T]all need the parameter, because the lifetime appears inside the type. - Generic fields. A field of type
TwhereTmay itself be a reference is covered by lifetime bounds in a later chapter. - Derives.
#[derive(Debug, Clone)]works onExcerpt<'a>.Clonecopies the reference, not the text.
Borrow or own?
A borrowing struct is cheap, because it copies no data. It also ties the struct to its owner's scope. That makes it a poor fit when the value must be returned from a function that created the data, stored in a long-lived collection, or sent to another thread.
| Situation | Better choice |
|---|---|
| Short-lived view over input, such as a parser or iterator | Borrow with `&'a str` |
| Value stored in a long-lived struct or returned upward | Own with `String` |
| Many small values from one large buffer | Borrow, if the buffer outlives them |
| Compiler errors keep growing with every new field | Own, then optimize later |
Common errors with borrowing structs
| Error | Cause | Fix |
|---|---|---|
| E0106 missing lifetime specifier | A reference field has no lifetime | Add `<'a>` to the struct and `&'a` to the field |
| E0597 does not live long enough | The struct is used after its source is dropped | Extend the owner's scope, or store an owned value |
| E0505 cannot move out while borrowed | The owner was moved while a struct still borrows it | Use the struct before the move, or clone the data |
| E0499 second mutable borrow | A method result is tied to `&mut self` through elision | Return `&'a T` where `'a` is the struct's parameter |
Exercise
The struct struct Token { text: &str, line: u32 } fails with E0106. Fix it. Then write fn first_token(src: &str) -> Token<'_> that returns a Token whose text is the first whitespace-separated word of src (an empty string if there is none) and whose line is 1.
Show answer
Add a lifetime parameter and use it in the reference field:
struct Token<'a> { text: &'a str, line: u32 }
fn firsttoken(src: &str) -> Token<'> {
Token { text: src.splitwhitespace().next().unwrapor(""), line: 1 }
}
Only text needs 'a, because line is an owned u32. Elision gives the single input lifetime of src to '_, so the returned Token is valid as long as src is.
Exercise
In Words<'a>, change next_word to return Option<&str> instead of Option<&'a str>. In main, first and second are then both used after the second call. Which error appears, and why?
Show answer
E0499, cannot borrow words as mutable more than once at a time. With the elided signature, the returned reference gets the lifetime of the &mut self borrow. first keeps that borrow alive, so the second call to next_word needs a second mutable borrow while the first is still in use. Returning &'a str ties the result to the original text instead.