0

I'm confused about Rust's behavior in the following example.

This example fails:

let mut coll = vec![1, 2, 3].iter();
some_consuming_fn(&mut coll);
error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:4:20
  |
4 |     let mut coll = vec![1, 2, 3].iter();
  |                    ^^^^^^^^^^^^^       - temporary value is freed at the end of this statement
  |                    |
  |                    creates a temporary which is freed while still in use
5 |     some_consuming_fn(&mut coll);
  |                       --------- 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)

However, if you call the iterable conversion as a function argument everything works fine.

let coll = vec![1, 2, 3];
some_consuming_fn(&mut coll.iter());

I'm confused about the ownership rules of a collection that's been turned into an iterable. Why would a call to some_iterable.iter() drop immediately after being called?

For reference, some_consuming_fn has the signature:

some_consuming_fn(x: &mut Iter<u32>) -> Foo;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
MFave
  • 1,044
  • 2
  • 8
  • 19
  • I believe your question is answered by the answers of [Why is it legal to borrow a temporary?](https://stackoverflow.com/q/47662253/155423). If you disagree, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Apr 20 '19 at 13:52
  • Yes, that question answers this one. – MFave Apr 20 '19 at 15:57
  • _I'm confused about the ownership rules of a collection that's been turned into an iterable._ -- calling `.iter()` does not turn it into an iterator, it returns an iterator that references the original. `.into_iter()` actually turns it into an iterator that owns the collection - you can use that instead. – harmic Apr 20 '19 at 23:48

0 Answers0