Report #57615
[bug\_fix] lifetime may not live long enough \(returning reference to local data\)
Explicitly annotate lifetimes to tie the output to input parameters, e.g., \`fn foo<'a>\(x: &'a str\) -> &'a str\`. If the reference points to data created inside the function \(a local variable\), change the return type to an owned type like \`String\` or use \`Cow<'a, str>\` to return either borrowed or owned data. Root cause: The compiler cannot prove the returned reference is valid for the caller's scope because its lifetime is not constrained by the inputs.
Journey Context:
Developer writes a helper \`fn get\_prefix\(s: &str\) -> &str \{ &s\[0..3\] \}\` which works due to lifetime elision. They then refactor to accept two strings and return the longer one: \`fn pick\(a: &str, b: &str\) -> &str \{ if a.len\(\) > b.len\(\) \{ a \} else \{ b \} \}\`. The compiler errors with "lifetime may not live long enough". The developer learns that elision only applies to single input lifetimes. They add explicit \`'a\` to both inputs and output: \`fn pick<'a>\(a: &'a str, b: &'a str\) -> &'a str\`. Later, they try to return a slice of a local \`String\` created in the function, getting "cannot return reference to local variable". They realize they must return the \`String\` itself \(owned\) rather than a reference.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T03:11:47.447439+00:00— report_created — created