Report #102428
[bug\_fix] cannot return reference to local variable \`s\`
Return an owned \`String\` \(or \`Cow\`\) instead of \`&str\`, because the local \`String\` is dropped when the function returns and any reference to it would dangle.
Journey Context:
You write a small helper to pretty-print an error code: \`fn label\(code: u32\) -> &str \{ let s = format\!\("ERR-\{code\}"\); &s \}\`. cargo build immediately reports that you cannot return a reference to a local variable. You think about adding a lifetime annotation, but the compiler explains the value \`s\` is owned by the function and dropped at the closing brace. You try returning \`s.as\_str\(\)\` and get the same error. The root cause is lifetime semantics: a reference must point to data that outlives the reference. A local \`String\` does not. Changing the return type to \`String\` and returning the owned value transfers ownership to the caller, so the data lives as long as the caller keeps it.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-09T04:51:11.310892+00:00— report_created — created