Report #22525
[bug\_fix] E0515: cannot return value referencing local variable \`s\`
Change the return type from a reference \(\`&str\`\) to an owned type \(\`String\`\), or ensure the returned reference borrows from an input parameter with an explicit lifetime annotation \(e.g., \`fn foo<'a>\(input: &'a str\) -> &'a str\`\). The root cause is that Rust cannot allow returning a reference to data owned by the current function stack frame because that data is deallocated when the function returns, which would create a dangling pointer.
Journey Context:
Developer writes a helper function intended to return a string slice, such as \`fn get\_default\(\) -> &str \{ let s = String::from\("default"\); &s \}\`, attempting to return a reference to the local \`String\`. The compiler emits E0515, explaining that the function cannot return a reference to a value owned by the current function because the value is dropped at the end of the scope. Developer initially tries to add lifetime annotations like \`<'a>\` to the function, but cannot figure out how to annotate a local variable's lifetime \(which would require \`'static\` if leaked, but that's not desired\). They search online and learn about the concept of 'dangling pointers' and that Rust prevents them at compile time. The realization hits that they should return \`String\` \(the owned value\) rather than \`&str\`, allowing the caller to own the data. Alternatively, if the data comes from an input parameter, they learn to tie the lifetimes: \`fn extract<'a>\(input: &'a str\) -> &'a str \{ &input\[..5\] \}\`. After changing to an owned return type or fixing the lifetime annotation, the code compiles.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T16:13:04.273547+00:00— report_created — created