skip to content

On a Rust `TextBuffer<'a>` holding `&'a str`, why does `TextBuffer::new(&src).first_line()` fail with E0716 when `first_line(&self) -> &str` relies on elision?

level: seniorimportance: should knowfreq 32%

answer

  1. two lifetimes: the view and its source
  2. elision picks the receiver's borrow
  3. the temporary dies at statement end
  4. return &'a str instead

basics

~20 s

Elision ties first_line's result to the borrow of self, the temporary TextBuffer, not to 'a, the source text. The temporary is freed at the end of the let statement, so the result cannot be used afterwards: E0716. Returning &'a str fixes it.

solid answer

~40 s

In `impl<'a> TextBuffer<'a>`, the elided `fn first_line(&self) -> &str` expands to `fn first_line<'s>(&'s self) -> &'s str`: the receiver rule assigns the output the lifetime of the borrow of `self`, and `'a` from the impl header is not an input lifetime of the method. `TextBuffer::new(&src)` creates a temporary that is freed at the end of the `let` statement, so a result tied to borrowing it cannot be used on the next line: `error[E0716]: temporary value dropped while borrowed`. Yet the slice really points into `src`, which is still alive. Writing `fn first_line(&self) -> &'a str` says so, and the chained call compiles. rustc's own help, binding the temporary with `let`, also compiles, but leaves a signature tighter than the data it returns.

code

plaintext · 9 lines
plaintext
error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:8:17
  |
8 |     let first = TextBuffer::new(&src).first_line();
  |                 ^^^^^^^^^^^^^^^^^^^^^             - temporary value is freed at the end of this statement
  |                 |
  |                 creates a temporary value which is freed while still in use
9 |     println!("{first}");
  |                ----- borrow later used here

go deeper

for a junior

Know that a struct can hold a reference with a lifetime parameter, and that a method returning &str is by default tied to the borrow of self.

for a middle

Expand first_line to show the output takes the receiver's lifetime, and explain that impl-header lifetimes such as 'a are not inputs for method elision.

for a senior

Diagnose E0716 on a chained temporary by asking where the returned data really lives, and return &'a str when it points into the borrowed source instead of adding a binding.

for a principal

Audit getters on borrowing types as API surface: an elided return tied to self forces every caller to keep the view alive, which limits how views and parsers compose.

## Two lifetimes in one call A type such as `struct TextBuffer<'a> { src: &'a str }` is a **borrowing view**: it does not own its text, it points into a `String` someone else owns. Any method call on it involves two different lifetimes: - **`'a`**, how long the source text is borrowed for. It belongs to the type and outlives every individual `TextBuffer` value built from that source. - **The receiver borrow**, how long this particular call borrows the `TextBuffer` value itself through `&self`. It can be much shorter, down to a single statement. The question for every method that returns a reference is which of the two the result is tied to. ## What elision picks Elision answers by rule, not by reading the body. Lifetimes declared on the `impl` header, here `'a`, are **not input lifetimes of the method**; only the method's own parameter types count. In `fn first_line(&self) -> &str` the receiver `&self` is `&'s TextBuffer<'a>`, and the receiver rule assigns `'s`, the borrow of the value, to the elided output: ```rust fn first_line(&self) -> &str // elided fn first_line<'s>(&'s self) -> &'s str // what elision means fn first_line(&self) -> &'a str // what the data allows ``` The body returns a slice of `self.src`, which has type `&'a str`. Because `'a` outlives `'s`, returning it as `&'s str` is accepted: the elided signature compiles, it just promises **less** than the data supports. ## Why the temporary matters That weaker promise is invisible until a caller uses the method on a short-lived value. In `let first = TextBuffer::new(&src).first_line();`, the `TextBuffer` is a **temporary**: it is never bound to a name, and it is freed at the end of the `let` statement. Under the elided signature `first` borrows that temporary, so the next line's use of `first` is rejected with `error[E0716]: temporary value dropped while borrowed`. The source string `src` is fine throughout; the error is about the view, not the data. The same weaker promise shows up without a chained call. A helper `fn title_of(src: &str) -> &str` that builds a local `TextBuffer`, calls `first_line` and returns the result fails with ``error[E0515]: cannot return value referencing local variable `buf` ``, because the result borrows the local view, even though the text it points into belongs to the caller. With `-> &'a str` on `first_line`, that helper compiles as well. ## The fix and what changes | | `-> &str` (elided) | `-> &'a str` | |---|---|---| | Result tied to | the borrow of the `TextBuffer` value | the source text | | Chained call on a temporary | E0716 | compiles | | Result kept after the view is dropped | rejected | allowed | | Right when | the data is owned by the struct | the data lives in the borrowed source | rustc's help for `E0716` suggests binding the temporary first (`let binding = TextBuffer::new(&src);`). That compiles too, but it treats the symptom: every caller must keep the view alive for as long as it uses a result that never needed the view. The same pattern appears in std. The `str` iterators such as `std::str::Lines<'a>` implement `Iterator` with `type Item = &'a str`, so `next(&mut self)` yields slices of the original string, not of the iterator, and you can collect the lines and drop the iterator. ## Review checklist for borrowing types - For each method returning a reference, ask whether the data lives **in the struct** or **in what the struct borrows**. - Owned fields such as `String` or `Vec<T>`: the elided signature is correct, since the data can only be borrowed through `self`. - Borrowed fields such as `&'a str`: return `&'a str` unless you deliberately want results to keep the view borrowed. - Constructors are the mirror case: `fn new(src: &'a str) -> Self` already names `'a` through `Self`, so nothing is elided there; the question only arises in methods that return references. - `&mut self` methods deserve extra care: an elided result keeps the whole value **mutably** borrowed while it is used. - Declaring and designing the borrowing struct itself, when to hold `&'a str` versus owning a `String`, is a separate subject covered with structs that hold references.

  • Why are lifetimes from the impl header not input lifetimes for elision in a method?
    Elision reads only the method's own parameter types. The Rustonomicon states that the input positions of a method do not include lifetimes in its impl header. So in `impl<'a> TextBuffer<'a>`, the receiver rule hands the output the lifetime of the `&self` borrow; `'a` is in scope inside the method, but it only reaches an output if you write it.
  • Is returning `&'a str` from a `&self` method ever wrong?
    Yes, when the data lives in the struct itself. A `TextBuffer` that owns a `String` has no `'a`; a slice of that string can only be borrowed through `self`, and the elided signature is exactly right. `&'a str` fits only when the struct holds a `&'a str` and the method returns part of that borrowed text.
  • Which std iterator follows the same pattern?
    `std::str::Lines<'a>` implements `Iterator` with `type Item = &'a str`, as do the other `str` iterators. `next(&mut self)` therefore returns slices tied to the original string, not to the iterator, which is why `text.lines().collect::<Vec<&str>>()` can outlive the iterator that produced it.

  • Lifetimes declared on the impl header count as inputs for method elision.
  • The elided output of first_line automatically takes the struct's 'a parameter.
  • E0716 here means src was dropped too early.
  • Binding the TextBuffer to a variable is the only way to fix it.
  • Returning &'a str from a &self method is unsound because it outlives self.