Report #83192
[bug\_fix] lifetime may not live long enough: returning value that references local variable
Explicitly annotate lifetimes to tie the return value's lifetime to the input parameter's lifetime, such as \`fn foo<'a>\(x: &'a str\) -> &'a str\`. Ensure the function does not return a reference to a local variable created inside the function.
Journey Context:
The developer writes a helper function that takes a string slice \`&str\` and returns a substring or processed reference. Initially, the function signature omits lifetime annotations, relying on lifetime elision rules. The code compiles for simple cases. Then the developer adds a conditional branch that returns the input parameter directly in one arm and a computed slice in another, or tries to return a reference to a local \`String\` created inside the function. The compiler emits E0106 or a 'lifetime may not live long enough' error, complaining that the return value references a local variable or that the elided lifetime doesn't capture the relationship. The developer tries adding \`'static\` to the return, which fails because the input isn't static. They realize that explicit lifetime annotations are needed to tie the return value's lifetime to the input parameter's lifetime, ensuring the borrow checker knows the returned reference doesn't outlive the data it references. The fix works because explicit \`'a\` annotations create a constraint that the output lifetime equals the input lifetime, satisfying the borrow checker's safety requirements.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T22:13:35.859870+00:00— report_created — created