Sub topic 15
Structs that borrow data
This chapter covers structs whose fields are references instead of owned values. It assumes you know ownership, & and &mut borrows, how to write impl blocks, and how to run a program with cargo. You should also have seen lifetime names such as 'a in function signatures.
Why a struct would hold a reference
Most structs in this tutorial own their data. A String field owns its text. When the struct is dropped, the text is dropped too.
Sometimes you don't want to copy. A parser might look at a large input string and hand back pieces of it. Copying every piece costs memory and time. A struct can instead hold a reference, a &str that points into text owned somewhere else.
The compiler must be sure the reference never outlives the data it points to. A lifetime parameter is how you tell it the relationship.
Declaring a lifetime parameter
A reference field needs a lifetime in its type. The struct declares the lifetime name in angle brackets, then uses it in the field.
struct Excerpt<'a> {
text: &'a str,
}Read this as: an Excerpt cannot live longer than the &str it holds, and 'a names that bound. Leaving the lifetime off is an error:
struct Excerpt {
text: &str, // error[E0106]: missing lifetime specifier
}Function signatures can often omit lifetimes because of elision rules. Struct fields have no such rule, so you always write them.
Using the struct
struct Excerpt<'a> {
text: &'a str,
}
impl<'a> Excerpt<'a> {
fn first_word(&self) -> &str {
self.text.split_whitespace().next().unwrap_or("")
}
}
fn main() {
let text = String::from("structs and methods");
let ex = Excerpt { text: &text };
println!("{}", ex.first_word());
}Here text is owned by main. ex borrows it. Because text is declared first, it is dropped last, so the borrow stays valid for the whole life of ex.
Lifetimes in `impl` blocks
The impl line has two parts. In impl<'a> Excerpt<'a>, the first <'a> declares the lifetime name. The second Excerpt<'a> uses it, like generic type parameters in impl<T> Pair<T>.
Inside methods, elision rules fill in the rest. In first_word(&self) -> &str, the returned reference gets the lifetime of &self. That is the rule for methods with a &self receiver.
This is safe but can be more restrictive than you need. The returned &str is tied to the borrow of ex, not to the original text. Consider a method that should return something living as long as the underlying text:
struct Excerpt<'a> {
text: &'a str,
}
impl<'a> Excerpt<'a> {
fn first_word(&self) -> &'a str {
self.text.split_whitespace().next().unwrap_or("")
}
}
fn main() {
let text = String::from("structs and methods");
let word;
{
let ex = Excerpt { text: &text };
word = ex.first_word();
}
println!("{}", word);
}This compiles because the return type names 'a. The word is tied to text, so it remains valid after ex goes out of scope. With the elided version, word would be tied to ex, and using it after the inner block would be a borrow error.
| Signature | Returned reference lives as long as | Can outlive the struct value? |
|---|---|---|
| `fn first_word(&self) -> &str` | the borrow of `self` | No |
| `fn first_word(&self) -> &'a str` | the data the struct points to | Yes |
Use &'a str when callers should be able to keep the result after dropping the struct. Use the elided form when the result really depends on the struct.
What the compiler rejects
The struct cannot outlive its source. This program fails:
struct Excerpt<'a> {
text: &'a str,
}
fn main() {
let ex;
{
let text = String::from("short lived");
ex = Excerpt { text: &text };
}
println!("{}", ex.text);
}The error is E0597: text does not live long enough. text is dropped at the end of the inner block, but ex is used afterward. The lifetime 'a would need to cover the println!, and text doesn't last that long.
Mutable references and exclusivity
A struct can hold &'a mut T. While the struct exists, the original data is mutably borrowed, so nothing else can read or write it.
struct Counter<'a> {
count: &'a mut u32,
}
impl<'a> Counter<'a> {
fn bump(&mut self) {
*self.count += 1;
}
}
fn main() {
let mut total = 0;
{
let mut c = Counter { count: &mut total };
c.bump();
c.bump();
}
println!("{}", total);
}The inner block matters. Printing total while c is still in use would be an error. With modern non-lexical lifetimes, the borrow ends after the last use of c, so the block is optional here, but it makes the scope explicit.
Several lifetimes
A struct can hold references from different sources. Give each its own name when they are independent.
struct Pair<'a, 'b> {
left: &'a str,
right: &'b str,
}
fn main() {
let a = String::from("alpha");
let p;
{
let b = String::from("beta");
p = Pair { left: &a, right: &b };
println!("{} {}", p.left, p.right);
}
}One lifetime would work here, since the compiler picks the shorter region. Separate names matter when a method must return only one side with its own longer lifetime. Start with one lifetime and add more only when a signature requires it.
Owned or borrowed: choosing
| Choose owned fields (`String`, `Vec<T>`) when | Choose borrowed fields (`&'a str`) when |
|---|---|
| The struct is stored long term, returned from functions, or sent to another thread. | The struct is a short-lived view over data that outlives it. |
| You want a simple type with no lifetime parameter. | Copying is costly and the source is stable. |
| Callers should not have to keep the source alive. | You are writing a parser, tokenizer, or iterator. |
A lifetime parameter spreads. Every struct that contains an Excerpt<'a> needs a lifetime too, and so does every function signature that mentions it. If that becomes painful, switching to owned fields is a reasonable fix.
Common errors
- E0106, missing lifetime specifier. A reference field has no lifetime. Add
<'a>to the struct and&'ato the field. - E0597, value does not live long enough. The source is dropped while the struct is still used. Declare the source earlier or in an outer scope.
- E0515, returns a reference to local data. A constructor built an owned
Stringinside the function and tried to put&stringin a returned struct. Take the&'a stras a parameter, or make the field owned. - Forgetting
<'a>onimpl. Writingimpl Excerpt<'a>withoutimpl<'a>fails with an undeclared lifetime error. - Returning a result tied to
&selfby accident. If callers cannot keep a result as long as the source, check whether the signature should return&'a T.
Exercise
A struct View<'a> has a field data: &'a str and a method fn head(&self) -> &str. A caller wants to keep the returned value after Plan view is dropped, while the source String is still alive. What change to the method makes that possible, and why?
Show answer
Change the return type to &'a str, giving fn head(&self) -> &'a str. With elision, the result is tied to the borrow of &self, so it cannot outlive the View. Naming 'a ties it to the underlying String, which stays alive after the View is dropped.
Exercise
This code fails with E0106. Fix it so it compiles, and say what the fix means. struct Token { text: &str }
Show answer
Write struct Token<'a> { text: &'a str }. The lifetime parameter says a Token cannot outlive the string slice it points to. Any impl block then needs impl<'a> Token<'a>.