skip to content

In Rust, why can't a `Document` struct own its `String` text and also hold `&str` slices into that same text?

level: seniorimportance: should knowfreq 55%

answer

  1. who chooses 'a
  2. a move is a bitwise copy
  3. loans on places, not addresses
  4. offsets instead of pointers

basics

~20 s

No lifetime can name the struct's own field: 'a must come from a borrow outside the value. A constructor fails with E0515 and E0505, and a value built in place is frozen. Store offsets, or split owner and view.

solid answer

~40 s

A lifetime parameter is chosen by whoever creates the struct, from a borrow that already exists, so nothing can say "borrows my own `text` field". A constructor that slices `text` and moves it into the struct fails with E0515 and E0505 ("cannot move out of `text` because it is borrowed"). Assigning `doc.title = doc.text.lines().next().unwrap_or("")` after construction compiles, but the value then borrows itself: moving it is E0505 and mutating `text` while `title` is used is E0502. The rule protects moves, which are bitwise copies; the borrow checker tracks loans on places rather than heap addresses, and `push_str` could reallocate anyway. The usual designs are `Range<usize>` offsets into the owned text, an owner plus a separate borrowing view type, or a shared `Rc<str>` buffer with ranges.

code

rust · 14 lines
rust
struct Document<'a> {
    text: String,
    title: &'a str,
}

fn load<'a>(text: String) -> Document<'a> {
    let title = text.lines().next().unwrap_or("");
    Document { text, title }
}

fn main() {
    let d = load("Title\nbody".into());
    println!("{}", d.title);
}

go deeper

for a junior

Recall that a Rust struct cannot hold a reference to one of its own fields, and that storing positions instead of references is the common workaround.

for a middle

Explain that 'a is chosen outside the value and walk through the E0515 and E0505 errors a constructor produces.

for a senior

Explain why the value built in place is frozen, why moves forbid self-borrows even for heap data, and pick offsets, a split view or a shared buffer.

for a principal

Treat a self-referential design as a signal to separate ownership from views in the API, and require any unsafe workaround to carry an audited invariant.

## The shape people try A document parser wants to read the file once and keep both the text and pointers to its parts: ```rust struct Document<'a> { text: String, title: &'a str, // meant to point into `text` } ``` The definition compiles; `'a` is just a parameter. The trouble is that **no lifetime name means "this struct's own field"**. `'a` must be chosen by whoever creates the value, from a borrow that already exists outside it, and the struct's own `text` does not exist outside it. ## What rustc says Writing a constructor exposes the problem at once. `fn load<'a>(text: String) -> Document<'a>` that slices `text` and then moves it into the struct fails twice in rustc 1.99.1: - **E0515** "cannot return value referencing function parameter `text`": the slice borrows a local that the function owns; - **E0505** "cannot move out of `text` because it is borrowed": moving `text` into the struct while `title` still borrows it. You *can* build one in place, by creating the struct with an empty `title` and then assigning `doc.title = doc.text.lines().next().unwrap_or("");`. That compiles, but the value is now borrowing itself, and it is frozen while that borrow is used: 1. `let moved = doc;` is **E0505** "cannot move out of `doc` because it is borrowed". 2. `doc.text.push_str("!")` followed by a use of `doc.title` is **E0502**, a mutable borrow while the immutable one is live. 3. If `Document` implements `Drop`, the self-borrow is rejected even with no move or mutation: **E0713** "borrow may still be in use when destructor runs", because the destructor could read `title` at scope end. So the value can never be returned from a function or stored anywhere else, which defeats the purpose. ## Why the rule exists In Rust, a **move is a bitwise copy** of the value to a new location, after which the old location is dead. A reference into the value's own bytes would still point at the old location. For inline data, such as a `[u8; 64]` buffer field, that is a dangling pointer at once. A `String` keeps its bytes on the heap, so moving the struct would *not* move them, but the borrow checker does not reason about addresses: it tracks **loans on places**, and `doc.text` is a place inside `doc`. It also has to cover mutation, since `push_str` may reallocate the heap buffer and leave the slice dangling anyway. Rejecting the pattern outright is what keeps every move a plain copy with no fix-up step. ## Designs that work | Approach | How it works | Cost | |---|---|---| | **Offsets** | store `Range<usize>` per section, slice on access | a bounds-checked slice per access; offsets must stay in sync with the text | | **Split owner and view** | caller keeps the `String`; a `DocumentView<'a>` borrows it | two types; the view carries `'a` | | **Shared buffer** | `Rc<str>` or `Arc<str>` plus ranges, cloned cheaply | a reference count; still offsets underneath | | **Unsafe encapsulation** | raw pointers behind a safe API, often from a crate | an unsafe invariant someone must audit | **Offsets** are the usual first answer: the struct owns everything, so it moves freely, and `fn section(&self, i: usize) -> &str` hands out slices tied to `&self`, which is exactly the borrow that keeps the text alive. **Splitting** keeps zero-copy access when the owner naturally lives longer, such as a buffer read in `main` and a view passed down the call stack: the caller writes `let text = std::fs::read_to_string(path)?;` and then `let view = DocumentView::parse(&text);`, and the view's `'a` is simply the borrow of that local. Both values sit side by side in the caller's scope instead of one inside the other, which is all the borrow checker needs. ## Where Pin fits Futures generated by `async fn` *are* self-referential, and Rust handles them with `Pin`, which promises the value will not move again. That machinery, and why ordinary structs do not use it, belongs to the material on async and pinning; for a plain parser type, offsets or a split design are simpler and need no `unsafe`. ## What to say in an interview - A struct cannot hold a reference to its own field because no lifetime can name the struct itself. - Building one in place compiles but freezes the value: no move, no mutation of the borrowed field. - Store offsets, split owner and view, or share the buffer; reach for unsafe last.

  • A `String` keeps its bytes on the heap, so moving the struct leaves them in place. Why is the self-reference still rejected?
    The borrow checker tracks loans on places such as `doc.text`, not where bytes live, and a move invalidates every loan on the moved place. It would also have to rule out mutation, since `push_str` can reallocate. Accepting it only for heap-backed fields would need address reasoning the checker does not do.
  • When is splitting into an owner and a borrowing view better than storing offsets?
    When the owner naturally outlives the view, such as a buffer read in `main` and a `DocumentView<'a>` passed down the call stack. Methods then return real `&'a str` slices with no per-access slicing, at the cost of a second type carrying a lifetime parameter.

A note inside a moving box that says the key is on the third shelf of this room goes wrong as soon as the box moves; a note that says the key is in the box's left pocket travels with it. Offsets are the second kind of note.

  • Declaring the struct as Document<'a> lets title borrow its own text field.
  • Boxing the text as Box<str> makes a self-reference accepted because the address is stable.
  • Wrapping the text in a RefCell solves the lifetime problem.
  • rustc rejects even building a self-borrowing value in place.
  • Moving a String copies its heap bytes, which is why the reference breaks.