error[E0716]: temporary value dropped while borrowed
You kept a reference into a temporary value, one that no variable holds. Rust drops temporaries at the end of the statement, so the reference would outlive its data.
Quick fix: Store the value in a variable first (let s = String::from(...);), then borrow from that variable.
Code that triggers E0716
fn main() {
let words: Vec<&str> = String::from("borrow checker rules").split(' ').collect();
println!("{words:?}");
}What the compiler says
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:2:28
|
2 | let words: Vec<&str> = String::from("borrow checker rules").split(' ').collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
3 | println!("{words:?}");
| --------- borrow later used here
|
help: consider using a `let` binding to create a longer lived value
|
2 ~ let binding = String::from("borrow checker rules");
3 ~ let words: Vec<&str> = binding.split(' ').collect();
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0716`.Why Rust raises E0716
String::from("borrow checker rules") creates a temporary String that no variable owns. Rust drops temporaries at the end of the statement, at the semicolon on line 2. split and collect produce &str slices that point into that temporary, so on line 3 words would be full of dangling references.
Rust extends a temporary’s life only in simple cases, such as let s = &String::new();. A method chain like this one doesn’t get that extension.
How to fix E0716
1. Bind the value to a variable first
Give the String an owner that lives as long as you need the slices. This is exactly what the compiler’s help suggests.
fn main() {
let sentence = String::from("borrow checker rules");
let words: Vec<&str> = sentence.split(' ').collect();
println!("{words:?}");
}2. Collect owned strings instead
If you don’t need the original string afterwards, turn each piece into an owned String before collecting. words then owns its data, and nothing borrows the temporary.
fn main() {
let words: Vec<String> = String::from("borrow checker rules")
.split(' ')
.map(String::from)
.collect();
println!("{words:?}");
}Related errors
- E0597: borrowed value does not live long enough
- E0515: cannot return reference to local variable
- E0106: missing lifetime specifier
Learn the concept behind it
The References and Borrowing lesson explains the rules behind E0716 with diagrams and more examples. For the official reference, run rustc --explain E0716 or read the E0716 entry in the Rust error index .
Hit a different error? Paste it into the Rust error lookup to find its fix.