Closed
Description
The following code:
fn main() {
let iter = vec![1, 2, 3].iter().map(|x| x * x);
for x in iter {
println!("{}", x);
}
}
Produces the following error:
error[E0716]: temporary value dropped while borrowed
--> foo.rs:2:16
|
2 | let iter = vec![1, 2, 3].iter().map(|x| x * x);
| ^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
3 |
4 | for x in iter {
| ---- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0716`.
Though the suggestion to make a let binding works, and is probably useful for other situations, it's not as elegant here:
fn main() {
let vec = complicated_get_vec();
let iter = vec.iter().map(|x| x * x);
for x in iter {
println!("{}", x);
}
}
The better solution to the compile error is to replace vec![].iter() ...
with vec![].into_iter()
, and the compiler error message may be updated to reflect this.
Metadata
Assignees
Labels
Area: Messages for errors, warnings, and lintsArea: Suggestions generated by the compiler applied by `cargo fix`Category: An issue proposing an enhancement or a PR with one.Diagnostics: An error or lint that needs small tweaks.Relevant to the compiler team, which will review and decide on the PR/issue.