Report #48741
[bug\_fix] cannot return value referencing local variable \`x\`
Return an owned \`String\` \(or \`Vec\`, etc.\) instead of \`&str\` by calling \`.to\_string\(\)\` on the slice, or restructure the function to accept \`&str\` and return \`&str\` with the same input lifetime, avoiding creation of local data. This ensures the returned data is owned by the caller \(or lives as long as the input\), preventing a dangling pointer.
Journey Context:
Developer writes a helper that trims whitespace: \`fn clean\(s: &str\) -> &str \{ let trimmed = s.trim\(\); trimmed \}\`. The compiler errors with “cannot return value referencing local variable \`trimmed\` which is owned by the current function.” Developer is confused because \`trim\` returns a slice of the input, but they’ve bound it to a local variable \`trimmed\` whose lifetime ends at the function scope. They try adding explicit lifetimes like \`-> &'static str\` which fails because the data isn’t static. They search the error code E0515 and read the Rust Book section on lifetimes. They realize that any reference created inside a function cannot outlive the function’s stack frame unless it’s derived from an input reference with the same lifetime. The fix is to either return \`s.trim\(\)\` directly without binding to a local, or change the return type to \`String\` and return \`s.trim\(\).to\_string\(\)\`, transferring ownership of the new string to the caller.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T12:17:58.696656+00:00— report_created — created