Report #15295
[bug\_fix] cannot return value referencing local variable \`s\`
Return an owned type \(\`String\`, \`Box\`, or \`Cow\`\) instead of a reference \(\`&str\`\). If the data must be borrowed, ensure the input data is passed by reference with an appropriate lifetime annotation and return a reference with the same lifetime.
Journey Context:
A new Rust developer writes a helper function \`fn extract\_token\(\) -> &str\`. Inside, they create a \`String\` using \`format\!\` or \`String::from\`, then attempt to return a slice \`&s\[0..4\]\`. The compiler errors immediately. The developer assumes adding explicit lifetimes \`'a\` to the function signature will fix it, writing \`fn extract\_token<'a>\(\) -> &'a str\`. The error persists. They search "rust return reference from function" and discover that references cannot outlive the data they point to, and local variables are dropped when the function returns. They realize the String must be owned by the caller, so they change the return type to \`String\` and use \`.to\_string\(\)\` or just return the \`String\` directly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T23:44:56.088597+00:00— report_created — created