Return owned values instead of dangling references
Quick answer
A reference cannot remain valid after the value it refers to has been destroyed. If a function creates new text locally and the caller needs that text afterward, return the owned String instead of a reference to it.
Return the resource, not a local borrow
Returning ownership moves the value to the caller, which can then keep it alive. Returning a reference to a local String would leave a reference without valid backing data. Lifetime annotations describe relationships; they cannot make a local owner survive. The invalid example uses an explicit 'static claim only to illustrate that it cannot repair the problem; lifetimes are taught later.
fn build() -> String { String::from("report") }fn main() { let report = build(); println!("{report}");}Expected stdout (not executed):
reportThe result belongs to main after build returns.
fn build() -> &'static String { let text = String::from("report"); &text}fn main() { println!("{}", build()); }Expected: compilation fails; exact diagnostic not verified.
The String is local to build and cannot support this returned reference.
Common mistake
Do not add 'static just to make the compiler accept a dangling reference; it does not change storage duration.
Try it yourself
Write a function that constructs an owned greeting and returns it; append punctuation in the caller.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Return owned values instead of dangling references — practice quiz
Choose one answer per question, then review the explanation.
Can adding a `'static` annotation make a reference to a locally created String valid after the function returns?
Which action transfers a newly constructed local String to the caller?
Why is returning a reference to a local String rejected?