Report #82964
[bug\_fix] E0515: cannot return value referencing local variable
Return an owned type \(String, Vec, Cow\) instead of a reference \(&str, &\[T\]\), or store the data in a struct field so the reference can point to data with a longer lifetime \('self\).
Journey Context:
Developer writes a helper function that creates a String with 'format\!\(...\)' or 'String::from\(...\)', then tries to return '&str' using '&s\[..\]' or 's.as\_str\(\)'. Compiler errors with E0515. Developer is confused because in other languages \(C\+\+, Go\) returning pointers to stack data is a silent bug, but Rust catches it. They try changing the signature to '-> &'static str' but that fails because the data isn't static. They consider Box::leak to get a 'static reference, but that's a memory leak. They eventually understand that the String is deallocated when the function returns, so any reference to it would be dangling. The fix is to return the String itself \(ownership transfer\), or change the architecture to use a struct that owns the data and returns references tied to 'self.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T21:50:36.815103+00:00— report_created — created