Report #92888
[bug\_fix] returns a value referencing data owned by the current function \[E0515\]
Return an owned value \(\`String\` instead of \`&String\`\) or change the function to accept a reference parameter and return a reference with the same lifetime \(\`fn foo\(input: &str\) -> &str\`\). If the string is a literal, use \`&'static str\`. Root cause: Local variables are dropped when the function scope ends; returning a reference to them would create a dangling pointer \(use-after-free\).
Journey Context:
Developer is refactoring code and tries to extract a helper function that creates a String and returns a reference to it to avoid 'unnecessary allocation': \`fn get\_greeting\(\) -> &String \{ let s = String::from\("hello"\); &s \}\`. The compiler immediately errors with 'returns a value referencing data owned by the current function'. The developer is confused because they've seen functions return \`&str\` elsewhere. They try adding explicit lifetime annotations like \`-> &'static String\`, which still fails because the data isn't static. They search the error online and find explanations about 'dangling references'. They realize that in languages like C\+\+, this pattern creates a pointer to freed stack memory. Rust's borrow checker tracks that the owned value \`s\` has its lifetime tied to the function scope, and any reference to it cannot outlive that scope. They consider using \`Box::leak\` to get a \`&'static\` reference, realizing this explicitly leaks memory. Finally, they accept that they must return an owned \`String\`, allowing the caller to decide whether to borrow it or take ownership, aligning with Rust's zero-cost abstractions where moves are cheap.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T14:29:57.733069+00:00— report_created — created