In Rust, why does `fn load_host<'a>() -> &'a str` returning `raw.trim()` of a local `String` fail with E0515, and why can no annotation fix it?
answer
- local dropped at function return
- output lifetime on no input
- caller chooses 'a
- return ownership instead
basics
~20 sraw is dropped when load_host returns, so a borrow of it would dangle, and rustc reports E0515. An output lifetime tied to no input lets the caller choose any lifetime, which only data valid everywhere, such as a literal, can satisfy.
solid answer
~40 s`raw.trim()` points into `raw`, which `load_host` owns and drops on return, so rustc reports `E0515: cannot return value referencing local variable raw`. An annotation cannot help because lifetimes describe relations between borrows, not how long values live. Worse, `'a` appears only in the output, so each caller may pick any lifetime for it, even `'static`; the only things a body can return for every choice are values valid everywhere, like a string literal. The fixes change ownership: return a `String` (`raw.trim().to_string()`), or take the raw text as a `&'a str` parameter and return a slice of it, so the result borrows the caller's buffer.
code
rust · 5 linesfn load_host<'a>() -> &'a str {
let raw = String::from(" db.internal ");
raw.trim()
}
fn main() { println!("{}", load_host()); }go deeper
Recall that a reference to a value created inside a function cannot be returned, because that value is dropped when the function returns; return an owned String instead.
Explain that an output lifetime appearing on no input is chosen by the caller, so only data valid everywhere satisfies it, which is why no annotation rescues E0515.
Choose the fix by ownership: return owned data when the function produces it, borrow from an input when it only selects, and treat unbound output lifetimes as a review smell.
Treat return types as ownership statements in API reviews: a borrowed return must name the input it borrows from, and anything the function creates is handed over as owned data.
## The failing function A helper loads a host name, trims the whitespace and tries to hand back the trimmed view: ```rust fn load_host<'a>() -> &'a str { let raw = String::from(" db.internal "); raw.trim() } ``` `str::trim` returns a `&str` that points into `raw`'s buffer. rustc 1.99.1 rejects the function: ```plaintext error[E0515]: cannot return value referencing local variable `raw` ``` with the labels "returns a value referencing data owned by the current function" and "`raw` is borrowed here". The error-code index states the rule: local variables, function parameters and temporaries are all dropped before the end of the function body, so a returned reference to such a value would immediately be invalid. ## Why no annotation can help A lifetime parameter describes how borrows *relate*; it cannot keep a value alive. Here the relation is impossible to satisfy: - `raw` is owned by `load_host` and dropped when the function returns. - A `&str` into `raw` is valid only inside the function body. - The signature promises a `&'a str` valid for `'a`, where `'a` is chosen **by the caller**. The last point is the one interviewers probe. `'a` appears in the output but in **no input**, so nothing ties it to anything the caller passed. Each caller may pick any lifetime it likes, including `'static`: ```rust let h: &'static str = load_host(); // accepted by the signature ``` The only values a body can return for every possible `'a` are ones valid everywhere, such as a string literal (`"db.internal"` compiles in this signature). A borrow of a local can never qualify, and no spelling of the annotation changes that. The Rust Book says the same: there is no way to specify lifetime parameters that would change a dangling reference. The same rule covers temporaries. A body that returns `String::from("db.internal").as_str()` fails with `error[E0515]: cannot return value referencing temporary value`, because the temporary `String` is dropped at the end of the statement, before the function returns. Writing no lifetime at all does not help either: `fn load_host() -> &str` fails earlier with E0106, whose help line notes there is no value for the result to be borrowed from and suggests returning an owned value. ## What the function can legitimately return | Return shape | Who owns the text | When to use it | |---|---|---| | `String` | the caller, after the move | the function creates or transforms the text | | `&'a str` from an input `&'a str` | the caller's own buffer | the function only selects a slice of what it was given | | a string literal as `&'static str` | the program binary | the value is a fixed constant | Two other shapes belong to other lessons: a clone-on-write type that is borrowed when no change was needed and owned otherwise, and leaking a heap allocation to obtain a `'static` borrow on purpose. ## Fixes, in order of preference 1. **Return an owned value.** `fn load_host() -> String` and `raw.trim().to_string()`. The caller now owns the text and decides when it is dropped. This costs one allocation and is usually right when the function produces the data. 2. **Borrow from an input instead.** If the caller already holds the raw text, take it as a parameter and return a slice of it: `fn trim_host<'a>(raw: &'a str) -> &'a str { raw.trim() }`. Now `'a` appears in an input, the result borrows the caller's buffer, and no copy is made. 3. **Return a constant.** If the value is truly fixed, return a literal with an explicit `&'static str`; that is a design statement, not a workaround. ## How to recognise the pattern Signals in a review: - an output lifetime that appears on no input is a red flag unless the body returns only data valid for the whole program; - E0515 means "you built it here, so you must hand over ownership or borrow from somewhere else"; - adding or renaming lifetime parameters in response to E0515 never works, because the data's owner, not the signature, is the problem; - an allocation in the fix is normal: returning `String` is the idiomatic answer when a function produces new text. The general shape of the reasoning: lifetimes connect outputs to inputs. When the output's data comes from neither an input nor a constant, there is nothing to connect it to, and the function must return ownership.
- Why does fn load_host<'a>() -> &'a str compile when the body returns the literal "db.internal"?A string literal is a `&'static str` stored in the binary, valid for the whole program, so it satisfies whatever `'a` the caller picks. The signature is accepted because every possible choice can be met, which is exactly what a borrow of a local cannot do.
- What changes when the raw text is passed in as a parameter?With `fn trim_host<'a>(raw: &'a str) -> &'a str`, the output lifetime is tied to an input. The result borrows the caller's buffer, valid as long as the caller keeps it, and no copy is made. Taking `raw: &String` but returning an unrelated `&'a str` fails with E0621.
- Adding a named lifetime to the return type fixes E0515.
- Returning &'static str makes the borrow of the local valid.
- The caller can extend raw's life by keeping the returned &str.
- An output lifetime is always tied to the function's own scope.