Sub topic 15
Structs that borrow data
This chapter assumes you know ownership, & and &mut references, and basic impl blocks. So far the structs in this tutorial owned their fields, such as String and u32. A struct can also hold a reference. Then it borrows data that lives somewhere else, and the compiler needs to know how long that borrow stays valid.
Why a lifetime parameter is needed
A field of type &str points at text owned by something else. The struct must not outlive that text, or the reference would dangle. Rust makes you state this relationship with a lifetime parameter:
struct Excerpt<'a> {
text: &'a str,
}'a is a name for "some span of time during which the borrowed data is valid". The declaration says that an Excerpt cannot live longer than the &str stored in it.
Methods on a borrowing struct
The impl block repeats the lifetime parameter. Write impl<'a> Excerpt<'a> so the compiler knows 'a is a parameter and not a type name.
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 prints structs. The return type is &'a str, not plain &str. The difference matters:
- With plain
&str, lifetime elision ties the result to the&selfborrow. The result could then not outliveex. - With
&'a str, the result is tied to the originaltext. It stays valid afterexgoes out of scope, asworddoes above.
If you change the return type to &str, the program no longer compiles, because word is used after ex is dropped.
Common errors
missing lifetime specifier: you wrotetext: &strin a struct. Add<'a>and&'a str.borrowed value does not live long enough: the struct outlives its source. This happens when the owner is declared in an inner block, or when you return the struct from a function while it borrows a local.cannot move out of ... because it is borrowed: you tried to move or mutate the owner while the struct still holds a reference to it.
Choosing between owned and borrowed fields
| Field type | Copies data | Struct can outlive the source | Needs lifetime parameter |
|---|---|---|---|
| `String` | Yes | Yes | No |
| `&'a str` | No | No | Yes |
Exercise
A struct has the field name: &'a str. A function builds a String locally, creates the struct from &local, and returns the struct. Why does this fail, and how do you fix it?
Show answer
The String is dropped when the function ends, so the returned struct would hold a dangling reference, and the compiler rejects it. Fix it by changing the field to an owned String, or by having the caller own the String and pass a reference in, so the struct's lifetime is tied to data that lives longer.