Report #83581
[bug\_fix] cannot return value referencing temporary value
Change the function signature to return an owned type \(e.g., \`String\` instead of \`&str\`\) or add a lifetime parameter to tie the return value's lifetime to an input parameter \(e.g., \`fn foo<'a>\(input: &'a str\) -> &'a str\`\). Root cause: The function attempts to return a reference to data that is owned by the function itself \(a temporary local variable\), which is dropped when the function returns, creating a dangling pointer. Rust's borrow checker prevents this memory safety error.
Journey Context:
A developer writes a helper function to normalize user input: \`fn normalize\(s: &str\) -> &str \{ s.trim\(\).to\_uppercase\(\).as\_str\(\) \}\`. They intend to trim whitespace and convert to uppercase, returning a string slice. Upon compilation, they receive E0515 pointing to the \`as\_str\(\)\` call, stating it references a temporary value created by \`to\_uppercase\(\)\`. The developer initially tries to return \`s.trim\(\)\`, which works because \`trim\` returns a slice of the input, but they need the uppercase version. They consider using \`lazy\_static\` or leaking the memory \(\`Box::leak\`\), which are inappropriate. They then realize that \`to\_uppercase\(\)\` produces a new \`String\` \(an owned allocation\), so a reference to it cannot outlive the function. The correct fix is changing the return type to \`String\` and returning the \`String\` directly \(or \`s.trim\(\).to\_uppercase\(\)\`\). The journey involved understanding stack frames, drop order, the difference between borrowed and owned data, and why \`as\_str\(\)\` on a temporary \`String\` creates a dangling reference.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T22:52:33.696249+00:00— report_created — created