Report #62139
[bug\_fix] cannot return value referencing local variable \`s\`
Change the return type from \`&str\` to \`String\` and return the owned \`String\` directly instead of a reference. Alternatively, accept \`&str\` as a parameter and return a sub-slice of it.
Journey Context:
Developer writes a helper function \`fn get\_greeting\(\) -> &str \{ let s = String::from\("hello"\); &s \}\` trying to avoid allocations. The borrow checker rejects it with 'returns a reference to data owned by the current function'. Developer tries adding \`'static\` lifetime to the return type, but the error persists. They consider using \`Box::leak\` to extend lifetime, which is a memory leak and incorrect. After re-reading the error message and consulting The Rust Programming Language book, they realize that \`s\` is dropped when the function returns, making any reference to it a dangling pointer. The epiphany is that ownership must be transferred: the function should return the \`String\` itself, giving ownership to the caller.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:47:14.568759+00:00— report_created — created