& vs iter() in for loop

Can someone tell me (or point me to a resource) the difference between:

for v in &my_array {

And:

for v in my_array.iter() {

Thanks in advance ! Have a good day all ! :slight_smile:

There is no difference between them in this form, but you must use the latter form if you want to make any further iterator operations on it, for example to also get indices to the elements, you could do this:

for (i, v) in my_array.iter().enumerate() {

but you can't do this:

for (i, v) in (&my_array).enumerate() {
1 Like

In case you are curious about why this works this way, the for loop uses the IntoIterator trait on the thing being iterated to covert it to the iterator. In the first case, the following impl for &[] is used:

https://doc.rust-lang.org/stable/src/core/slice/iter.rs.html#20-27

In the second case, .iter() returns an iterator, and each iterator implements IntoIterator thanks to this second impl:

https://doc.rust-lang.org/stable/src/core/iter/traits/collect.rs.html#236-243

4 Likes

Thanks for your answers! I suspected it was a such mechanism under the hood but now it's more clear. :slight_smile:

@Narann here are a series of slides put together with input from others that draw how the ways to generate an iterator work together in Rust.

1 Like

Nice! Thanks!