Sub topic 8
Structs that borrow data
This chapter assumes you know ownership and moves, the rules for &T and &mut T, and the difference between String and &str. You should also have read the earlier chapters on lifetime annotation syntax and function signatures.
Why a struct needs a lifetime parameter
A struct can hold a reference instead of owning its data. The compiler then has to know how long that reference stays valid. A struct value must never outlive the data it points to. Without that guarantee, the struct would contain a dangling reference.
For functions, elision often fills in lifetimes for you. For struct fields it does not. You must name the lifetime on the struct itself.
struct Excerpt {
part: &str,
}
// error[E0106]: missing lifetime specifierThis is error E0106. The fix is to declare a lifetime parameter 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> means that an Excerpt cannot outlive the string its part field points to. Here novel owns the text. first borrows from novel, and e borrows through first. All three are valid together until the end of main.
What the annotation does and does not do
The 'a does not set or extend how long anything lives. It only records a relationship. The struct value is valid for no longer than 'a, and 'a is limited by the owner of the borrowed data. The compiler checks every place an Excerpt is created or used against that relationship.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let novel = String::from("Call me Ishmael. Some years ago...");
e = Excerpt { part: &novel };
} // novel is dropped here
println!("{}", e.part);
}
// error[E0597]: `novel` does not live long enoughThe error appears at the borrow of novel, not at the struct definition. The definition only says "this struct borrows." Each use site must then prove the borrow is valid.
Several reference fields
Each reference field needs a lifetime. If two fields use the same 'a, they are tied to the same region, and the struct is valid only while both sources are alive. You can give fields separate parameters when the sources are unrelated.
struct Pair<'a, 'b> {
name: &'a str,
note: &'b str,
}
fn main() {
let name = String::from("config");
let pair;
{
let note = String::from("temporary");
pair = Pair { name: &name, note: ¬e };
println!("{} {}", pair.name, pair.note);
}
}Separate parameters make the struct harder to write and use. Start with one shared 'a. Add a second parameter only when a real caller needs the two sources to have different lifetimes.
Borrowing or owning
A lifetime parameter spreads. Every function, field, and type that holds an Excerpt<'a> must carry 'a too. That cost is worth paying when you want to avoid copying, for example in a parser that returns slices of its input. If the struct must be stored for a long time, sent to another thread, or returned from a function that created the data, own the data instead.
| Choice | Field type | Trade-off |
|---|---|---|
| Borrow | `&'a str` | No allocation, but the struct is tied to its source |
| Own | `String` | One allocation, but no lifetime parameter |
Common mistakes
- Writing
&strin a field without a lifetime, which gives E0106. - Returning a struct that borrows a local variable, which gives E0597 or E0515.
- Adding a second lifetime parameter "just in case" and complicating every signature.
Exercise
This function does not compile. Why, and how can you fix it? fn make() -> Excerpt<'static> { let s = String::from("hi"); Excerpt { part: &s } }
Show answer
The struct borrows s, which is dropped when make returns, so the reference would dangle (E0597 or E0515). 'static also claims the data lives for the whole program, which a local String cannot do. To fix it, change Excerpt to own a String, or pass the text in from the caller as fn make(s: &str) -> Excerpt<'_>.