Report #40360
[bug\_fix] cannot return reference to local variable \`s\` \(E0515\)
Return an owned value \(\`String\` instead of \`&str\`\) or accept the source data as a reference parameter with an explicit lifetime \`'a\` and return a reference tied to that input lifetime. Root cause: Local variables are dropped at the end of the function scope; returning a reference to them would create a dangling pointer, which Rust's borrow checker prevents.
Journey Context:
A new Rust developer writes a helper function \`fn get\_greeting\(\) -> &str \{ let s = String::from\("Hello"\); &s \}\` intending to return a string slice. The compiler immediately errors with E0515, stating it cannot return a reference to a local variable. The developer initially tries to add lifetime annotations \`<'a>\` randomly to the function signature, which only produces more confusing errors. They search the error code and read the Rust Book section on lifetimes. They realize that \`s\` is deallocated when the function returns, making any reference invalid. They change the return type to \`String\` and return \`s\` directly, transferring ownership. Alternatively, they refactor to accept \`&str\` as an argument and return a sub-slice of it with a proper lifetime annotation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T22:12:55.837279+00:00— report_created — created