Report #55072
[bug\_fix] cannot return reference to data owned by current function \[E0515\]
References must never outlive the data they point to. Since the \`String\` created with \`format\!\` or \`String::from\` is dropped when the function returns, any reference \`&str\` to it would be dangling. The fix is to return the owned \`String\` directly \(caller takes ownership\), or use \`std::borrow::Cow<'static, str>\` if the function sometimes returns a static string and sometimes a computed one. Never return \`&str\` pointing to a local \`String\`.
Journey Context:
Developer writes a helper function \`fn get\_name\(\) -> &str \{ let s = format\!\("user\_\{\}", id\); &s \}\` expecting to return a string slice. Compiler hits E0515 pointing at the return statement. Developer tries boxing it \`Box::leak\(s.into\_boxed\_str\(\)\)\` which stops the error but causes a memory leak. They search "return reference to local variable rust" and land on the Book chapter on Lifetimes. They read that the lifetime of the return value must be tied to input parameters or 'static. Realizing the data is owned by the function stack frame which is destroyed on return, they change the return type to \`String\`, update call sites to handle ownership, and remove the \`&\` borrow. The code compiles and Valgrind shows no leaks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T22:55:57.503051+00:00— report_created — created