Report #10121
[bug\_fix] cannot return reference to local variable \`x\`
Return an owned type instead of a reference \(e.g., return \`String\` instead of \`&str\`\), or take the source data as a function parameter with an appropriate lifetime annotation so the reference does not outlive the data.
Journey Context:
The developer writes a utility function intended to return a substring or a reference to data derived from a local variable: \`fn first\_word\(\) -> &str \{ let s = String::from\("hello world"\); &s\[..5\] \}\`. The compiler immediately flags this as an error, explaining that they cannot return a reference to data owned by the current function because \`s\` will be dropped when the function returns, leaving a dangling pointer. The developer initially tries to add lifetime annotations like \`-> &'static str\`, but realizes the data isn't static. They learn that references must always point to valid memory. The solution is to return the owned \`String\` directly, transferring ownership to the caller, or to restructure the function to accept \`&str\` as an argument: \`fn first\_word\(s: &str\) -> &str\`, allowing the caller to manage the lifetime of the data.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T09:51:12.424247+00:00— report_created — created