Temporary lifetime pitfalls
Quick answer
Temporary values often disappear at the end of their enclosing statement. Borrowing from them can produce a reference that is invalid when needed later.
Bind the owner explicitly
String::from(...).as_str() borrows the temporary String; storing that reference across statements is usually invalid. Some syntactic forms, such as a direct borrow in a let initializer, extend temporary lifetimes, but this is not a general rule for method calls. Edition-dependent temporary scopes also exist.
fn main() { let text = String::from("hello").as_str(); println!("{text}");}Expected: compilation fails; exact diagnostic not verified.
The String is dropped at the end of the let statement.
fn main() { let owner = String::from("hello"); let text = owner.as_str(); println!("{text}");}Expected stdout (not executed):
helloThe named String survives the reference use.
Common mistake
Do not assume that extending a variable's scope extends every temporary it borrowed from.
Try it yourself
Fix a similar temporary borrowing error using a named Vec owner and a slice.
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
Temporary lifetime pitfalls — practice quiz
Choose one answer per question, then review the explanation.
What is problematic about `let s = String::from("a").as_str();` followed by printing s?
Which rewrite keeps the owner alive explicitly?
Does every let initializer extend every borrowed temporary's lifetime?