Report #7620
[bug\_fix] cannot return reference to local variable \`s\` \(E0515\)
Change the return type from \`&str\` \(or \`&T\`\) to an owned type like \`String\` \(or \`T\`\). Alternatively, accept a mutable reference to a buffer \(\`&mut String\`\) and write into it. This fixes the root cause because local variables are allocated on the stack and are dropped when the function returns; returning a reference would point to deallocated memory \(a dangling pointer\), which Rust's lifetime system prohibits.
Journey Context:
Developer is writing a helper function to read a configuration string from a file. They define \`fn read\_config\(\) -> &str \{ let content = std::fs::read\_to\_string\("app.conf"\).unwrap\(\); &content \}\`, expecting to avoid the overhead of cloning a \`String\`. The compiler immediately flags E0515: 'cannot return reference to local variable \`content\`'. The developer tries to add a lifetime annotation \`-> &'a str\` and adds a generic lifetime parameter, but the error persists. They search 'rust return reference from function' and realize that the lifetime of \`content\` is strictly within the function scope; the moment the function ends, \`content\` is deallocated from the stack, making any reference invalid. The 'aha' moment comes when they understand that \`String\` is not just a pointer but an owned heap allocation that gets freed when the variable drops. They refactor to return \`String\` \(owned\), which moves the allocation out to the caller, or use a \`&mut String\` parameter to push into the caller's buffer.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T03:16:53.764665+00:00— report_created — created