Report #14301
[bug\_fix] cannot return reference to temporary value returns a reference to data owned by the current function
Change the return type from \`&str\` \(or \`&T\`\) to an owned type like \`String\` \(or \`T\`\), or change the function to accept a reference parameter and return a reference derived from that input \(extending the input's lifetime\). Root cause: Local variables \(including temporaries created by \`format\!\`\) are stored on the stack and dropped when the function returns; returning a reference to them would create a dangling pointer \(use-after-free\), which Rust's borrow checker prevents.
Journey Context:
Developer writes a helper function that constructs a formatted string: \`fn make\_greeting\(name: &str\) -> &str \{ let s = format\!\("Hello, \{\}\!", name\); &s \}\`. The compiler rejects this with an error about returning a reference to a temporary. The developer initially thinks they can force it with \`unsafe\` code or by using \`std::mem::forget\`, which leads to undefined behavior or memory leaks. After consulting documentation, they understand the ownership model: the String \`s\` owns its heap data and is dropped at the end of the function. The fix is to return the \`String\` itself, transferring ownership to the caller.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T21:13:51.221272+00:00— report_created — created