Report #55242
[bug\_fix] cannot return reference to temporary value
Return an owned \`String\` \(or \`Cow<'a, str>\`\) instead of \`&str\`. The temporary \`String\` created by \`format\!\` or similar is dropped at the end of the function, making any reference to it a dangling pointer. Changing the return type to \`String\` transfers ownership to the caller.
Journey Context:
You are writing a helper method to format an error code. You write \`fn error\_msg\(&self\) -> &str \{ format\!\("Error \{\}", self.code\) \}\`, expecting to return a string slice. The compiler slaps you with "cannot return reference to temporary value" and points to the \`format\!\` macro. You stare at it, confused, because it looks like you're returning a \`&str\`. You realize that \`format\!\` returns a \`String\`, and the \`&\` you're implicitly returning is a reference to that \`String\`'s internal buffer. But that \`String\` is a temporary local variable, dropped when the function ends, leaving the reference dangling. You consider using \`Box::leak\(format\!\(...\).into\_boxed\_str\(\)\)\` to leak the memory, but realize that's a permanent leak. You search online and find that the idiomatic fix is to change the return type to \`String\`, transferring ownership. You refactor all call sites, some of which were expecting \`&str\` and now need to handle an owned value, perhaps using \`as\_str\(\)\` where needed. The code now compiles and is memory-safe.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T23:13:00.053237+00:00— report_created — created