In Rust, with `pick<'a>` tying both `&str` inputs to its result, why does E0597 appear when one input's `String` drops before the result is used?
answer
- error at the call, not in pick
- 'a is the overlap of both borrows
- constrains, never extends
- last use after the drop
basics
~20 srustc picks 'a as the region where both borrows are valid, so the result cannot outlive the shorter-lived String. Using it after that String drops breaks the contract, and rustc reports E0597 against that argument at the call.
solid answer
~40 sWith `fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str`, rustc must find one region for `'a` that fits inside both borrows and covers every use of the result. If `override_host` is dropped at the end of an inner block and the result is printed afterwards, no such region exists, so rustc reports `E0597: override_host does not live long enough` at the call. The annotation never extends a value's life: drop points come from ownership and scope, and `'a` only tells the borrow checker which later uses to reject. Fixes: declare the `String` in the outer scope, use the result inside the block, or call `.to_string()` to take an owned copy before the drop.
code
rust · 13 linesfn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str {
if primary.is_empty() { fallback } else { primary }
}
fn main() {
let default_host = String::from("localhost");
let host;
{
let override_host = String::from("db.internal");
host = pick(&override_host, &default_host);
} // override_host is dropped here
println!("host = {host}");
}go deeper
Recall that the result of a function tying both inputs to one 'a is valid only while both inputs are, and that E0597 means a value was dropped while still borrowed.
Explain how rustc searches for one region for 'a that fits both borrows and covers every use, and why non-lexical lifetimes make the last use, not the scope end, decide.
Diagnose E0597 at a call by reading which inputs the callee ties to its output and where each is dropped, then fix the caller's scopes or an over-tight signature.
Set the expectation that call-site lifetime errors are fixed by restructuring ownership or by honest signatures, never by reaching for clones of references or 'static.
## The failing call Take a lookup whose signature ties both inputs to its result: ```rust fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str { if primary.is_empty() { fallback } else { primary } } ``` The function itself compiles. The trouble starts in a caller that builds the override in an inner block and prints the result after the block ends: ```rust let default_host = String::from("localhost"); let host; { let override_host = String::from("db.internal"); host = pick(&override_host, &default_host); } // override_host is dropped here println!("host = {host}"); ``` rustc 1.99.1 rejects it: ```plaintext error[E0597]: `override_host` does not live long enough ``` Read its three labels in order, because each marks a point you could move: - **the borrow**: `&override_host` in the call, labelled "borrowed value does not live long enough"; - **the drop**: the closing brace, labelled "`override_host` dropped here while still borrowed"; - **the use**: `host` in the `println!`, labelled "borrow later used here". The error exists because the use comes after the drop while the borrow is still needed. ## How rustc chooses `'a` A lifetime parameter is generic: at every call rustc looks for one concrete region to substitute for `'a` that satisfies the whole signature. - `&override_host` is valid only until the inner block ends, because `override_host` is dropped there. - `&default_host` is valid until the end of `main`. - The result has type `&'a str`, and `host` is used at the `println!`. For the code to be accepted, `'a` would have to cover the `println!` *and* fit inside both borrows. No such region exists: the borrow of `override_host` cannot reach past its drop. The annotation is a **constraint**, not an instruction, so rustc does not extend anything to make it fit. It reports the conflict. ## Why the error lands on the caller `pick` is correct. Its body only ever returns one of its arguments, which is exactly what its signature allows. The caller broke the contract by using the result after one of the inputs was gone, so the error names the argument that dies first. This is the practical meaning of "a lifetime annotation never extends a value's life": the value's drop point is fixed by ownership and scope, and the annotation only tells the borrow checker which later uses to forbid. Note that the error is **conservative**. At run time `override_host` is non-empty and `pick` would return it, but even if the program happened to return `default_host`, rustc would still reject the code: the signature says the result may come from either input, and the check uses the signature, not the run-time path. ## Ways to fix it 1. **Move the owner out.** Declare `override_host` beside `default_host`, so both outlive every use of `host`. 2. **Use the result inside the block.** If the last use of `host` is before the closing brace, the code compiles: since the 2018 edition, non-lexical lifetimes end a borrow at its last use, not at the end of the enclosing scope. 3. **Take ownership before the drop.** `pick(&override_host, &default_host).to_string()` produces an owned `String` that no longer borrows from either input. 4. **Question the signature.** If the result could only ever come from one input, tie only that input to the output, and callers may drop the other early. Here it really can come from either, so the single `'a` is honest. ## What does not help | Attempt | Why it fails | |---|---| | Swapping the argument order | both inputs share `'a`, so order changes nothing | | `.clone()` on the returned `&str` | cloning a `&str` copies the reference, which still borrows `override_host` | | Declaring the return type `&'static str` | the body then fails with "lifetime may not live long enough", because neither argument is known to be `'static` | The lesson for code review: when E0597 appears at a call, first check which inputs the callee's signature ties to its output, then check where each of those inputs is dropped. The fix is almost always in the caller's scopes or in a signature that ties more inputs than it needs to, never in an annotation that tries to stretch a value's life. Adding more lifetime parameters to `pick` would only change which callers are rejected, not make this caller's `override_host` last longer.
- Why does the same code compile if the println! moves inside the inner block?Since the 2018 edition, non-lexical lifetimes end a borrow at its last use rather than at the end of the scope. With the last use of `host` before `override_host` is dropped, a region for `'a` exists that fits both borrows, so the call is accepted even though `host` is declared outside the block.
- Would rustc accept the code if pick happened to return default_host at run time?No. The check uses the signature, which says the result may borrow from either input, so rustc must assume it borrows from the shorter-lived one. Run-time paths never enter the borrow check.
- Does calling .clone() on the returned &str fix the error?No. Cloning a `&str` copies the reference, which still borrows `override_host`, so E0597 remains. Converting to an owned `String` with `.to_string()` or `.to_owned()` ends the dependence on the input.
A visitor pass co-signed by two hosts is honoured only while both hosts are still in the building. Issuing the pass does not keep either host inside; when one leaves, the pass simply stops being honoured.
- The 'a annotation keeps override_host alive until the result is no longer used.
- pick's signature is wrong because the error mentions a borrow passed to it.
- Swapping the arguments makes the result depend only on default_host.
- Cloning the returned &str gives a copy that no longer borrows the input.
- rustc follows the run-time path to see which argument was returned.