Sub topic 14
Structs That Hold References
This chapter assumes you know the borrowing rules, how a function signature uses lifetime annotations like 'a, and the basic elision rules. It applies those ideas to struct fields.
Why a struct needs a lifetime
A struct with a String field owns that text, so the text lives as long as the struct. A field of type &str is different. It borrows text owned by someone else, and the struct must not outlive that text. Rust makes you state this with a lifetime parameter on the struct.
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 live longer than the string it borrows, which lasts for 'a." Here e is created after text and dropped before it, so the program compiles.
What the compiler checks
If the borrowed data is dropped while the struct is still in use, the borrow checker rejects the program. The commented-out line below is the one that would fail.
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let e;
{
let text = String::from("short lived");
e = Excerpt { part: &text };
}
// println!("{}", e.part); // error: `text` does not live long enough
let _ = e;
}The inner text is dropped at the closing brace. Using e afterwards would read freed memory, so Rust refuses to compile that line.
Methods on structs with references
Put the lifetime on the impl block and pass it to the type: impl<'a> Excerpt<'a>. Inside, you choose what each returned reference is tied to.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
// Elision: the result borrows from &self.
fn len(&self) -> usize {
self.part.len()
}
// The result is tied to the original text, not to &self.
fn text(&self) -> &'a str {
self.part
}
}
fn main() {
let text = String::from("Call me Ishmael.");
let kept: &str;
{
let e = Excerpt { part: &text };
println!("{}", e.len());
kept = e.text();
}
println!("{kept}");
}kept stays valid after e is dropped. That works because text() returns &'a str, which borrows from text and not from e. With an elided signature, fn text(&self) -> &str, the result would be tied to the borrow of e, and the last println! would not compile.
Summary of the rules
| Situation | What to write |
|---|---|
| Struct has a reference field | `struct S<'a> { f: &'a T }` |
| Implementing methods | `impl<'a> S<'a> { ... }` |
| Result should outlive the struct | Return `&'a T` |
| Result may be tied to the struct borrow | Return `&T` and let elision apply |
Exercise
In the third example, why does println!("{kept}") compile after e goes out of scope, and what single change to text's signature would make it fail?
Show answer
text returns &'a str, so the result is tied to the borrowed String named text, which is still alive. Changing the signature to fn text(&self) -> &str makes elision tie the result to the borrow of e, and e is already dropped, so the compiler reports an error.