skip to content

Why does the Rust method `fn line_or(&self, n: usize, fallback: &str) -> &str` fail to compile when it may return `fallback`?

level: middleimportance: should knowfreq 50%

answer

  1. the receiver claims the output
  2. fallback has an unrelated lifetime
  3. not E0106: a borrow-check error
  4. one named lifetime on both

basics

~20 s

Elision gives the output the lifetime of &self, while fallback gets its own unrelated lifetime, so returning fallback breaks the signature: lifetime may not live long enough. Name one lifetime on &self, fallback and the output, or return only data from self.

solid answer

~40 s

By rule 1, `&self` and `fallback` get distinct lifetimes; by the receiver rule, the elided output takes the lifetime of `&self`. The signature therefore promises a result borrowed from the buffer, and the body returns `fallback` on one path. rustc reports `error: lifetime may not live long enough`, with no E-code, because the signature itself is legal; the body breaks it. The fix states the real relationship: `fn line_or<'a>(&'a self, n: usize, fallback: &'a str) -> &'a str`, so the result may come from either source and is valid while both are. rustc's first help, which names `'a` only on `fallback` and the output, still fails, because the path returning a line of `self.text` then breaks the new signature; its next help adds `&'a self`.

code

plaintext · 9 lines
plaintext
error: lifetime may not live long enough
 --> src/main.rs:4:9
  |
3 |     fn line_or(&self, n: usize, fallback: &str) -> &str {
  |                -                          - let's call the lifetime of this reference `'1`
  |                |
  |                let's call the lifetime of this reference `'2`
4 |         self.text.lines().nth(n).unwrap_or(fallback)
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`

go deeper

for a junior

Know that a method returning a reference is assumed to borrow from self, and that returning another argument instead needs a named lifetime.

for a middle

Expand the signature to show the two distinct lifetimes, and explain why the fallback path in the body, not the signature, triggers lifetime may not live long enough.

for a senior

Choose between a shared lifetime, an Option return and a 'static fallback by what callers need, check every return path before accepting a suggestion, and change a trait declaration with its impls.

for a principal

Prefer method signatures whose borrows are obvious in elided form, such as returning Option and letting callers supply defaults, so a public API rarely needs named lifetimes.

## What the elided signature says `fn line_or(&self, n: usize, fallback: &str) -> &str` goes through the elision rules like this: - **Rule 1:** the receiver and `fallback` each get a fresh lifetime parameter. `n: usize` has none. - **Rule 3:** the receiver is `&self`, so its lifetime is assigned to the elided output. The expanded signature is therefore: ```rust fn line_or<'s, 'f>(&'s self, n: usize, fallback: &'f str) -> &'s str ``` Nothing relates `'f` to `'s`. The signature promises callers a string that borrows from the `TextBuffer` and may live as long as that borrow, whatever happens to the `fallback` argument. ## Why the body breaks it The body `self.text.lines().nth(n).unwrap_or(fallback)` returns either a line of the buffer, which has lifetime `'s`, or `fallback`, which has lifetime `'f`. The second path breaks the promise: a caller could pass a borrow of a temporary `String` as `fallback`, drop it, and still hold the result. rustc refuses: ```plaintext error: lifetime may not live long enough method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1` ``` Here `'2` is the receiver's lifetime and `'1` is the fallback's. The error has **no E-code**: it is not `E0106`, because the receiver rule filled the output lifetime and the signature is complete. The failure comes later, when the borrow checker compares the body with that signature. The program the error protects against is easy to write: ```rust let line = { let placeholder = String::from("<none>"); buf.line_or(7, &placeholder) }; // placeholder is freed here println!("{line}"); ``` Under the elided signature this caller looks fine, because `line` borrows only `buf`. If rustc accepted the body, `line` would point into the freed `placeholder`. With the shared-lifetime fix below, the same caller is rejected instead with ``error[E0597]: `placeholder` does not live long enough``, which is the honest answer. ## Why the first suggestion is not enough rustc first suggests `fn line_or<'a>(&self, n: usize, fallback: &'a str) -> &'a str`. That fixes the `fallback` path and breaks the other one: the line of `self.text` still has the receiver's own lifetime, which is now unrelated to `'a`. Compiling it gives the same `lifetime may not live long enough` error on the `self.text` path, and the help then suggests adding `'a` to `&self` as well. The lesson is to read every return path before accepting a suggestion. ## The fixes and what they cost | Fix | Signature | Effect on callers | |---|---|---| | Shared lifetime | `fn line_or<'a>(&'a self, n: usize, fallback: &'a str) -> &'a str` | Result valid while both the buffer borrow and `fallback` are | | Return `Option` | `fn line(&self, n: usize) -> Option<&str>` | Elision fits; caller writes `buf.line(7).unwrap_or(&missing)` | | `'static` fallback | `fn line_or(&self, n: usize, fallback: &'static str) -> &str` | Compiles elided; only literals and other static data accepted | | Owned result | `fn line_or(&self, n: usize, fallback: &str) -> String` | No borrow at all; allocates on every call | Choosing among them: 1. Use the **shared lifetime** when the method genuinely chooses between two borrowed sources and callers pass run-time strings. 2. Prefer the **`Option` return** for a public API: the signature stays elided, and the caller combines the result with a default at a call site where both lifetimes are visible. 3. Use **`&'static str`** only when the fallback is always a fixed placeholder. 4. Return **owned data** when the result must outlive both inputs. ## The general rule - The receiver rule is a **default**, not an inference from the body: rustc assigns `&self`'s lifetime to every elided output, whatever the body returns. - A `&self` method that may return data borrowed from another argument **always** needs a named lifetime that covers that argument. - In a trait, the declaration and every implementation must agree, which is why rustc's help says to update the trait if needed. - Generic lookups follow the same pattern: a method such as `fn get_or<'a>(&'a self, key: &str, default: &'a T) -> &'a T` names one lifetime on the receiver and the caller-supplied default, and leaves `key` elided because the result never borrows from it. - The same reasoning applies to `&mut self` methods; there the shared lifetime also keeps the value mutably borrowed while the result is in use.

  • Why does this error have no E-code when a two-input free function gets E0106?
    `E0106` is raised while resolving the signature, when an elided output has no rule to fill it. Here the receiver rule fills it, so the signature is valid. The failure appears later, when the borrow checker compares the body against that signature and finds a path returning data with a lifetime the signature never promised; rustc prints that as `error: lifetime may not live long enough`.
  • How does returning `Option<&str>` avoid the named lifetime entirely?
    `fn line(&self, n: usize) -> Option<&str>` returns only data from `self`, so the elided signature is exactly right. The caller supplies the default: `buf.line(7).unwrap_or(&missing)`. The borrow checker then checks the combined result at the call site, where both the buffer and `missing` are visible, and the method's signature never mentions the second source.
  • Does a `&'static str` fallback parameter fix it without any other lifetime?
    Yes: `fn line_or(&self, n: usize, fallback: &'static str) -> &str` compiles, because a `'static` borrow outlives the receiver's lifetime and so satisfies the elided output. It limits callers to string literals and other static data, so it suits fixed placeholders, not text computed at run time.

  • rustc reads the body and sees that the result may come from fallback.
  • The error is E0106 because the method has two reference inputs.
  • Adding 'a only to fallback and the return type is enough to fix it.
  • Cloning fallback into a String is the only way to make it compile.
  • A &self method can never return data borrowed from one of its arguments.