& vs iter() in for loop

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

for v in &my_array {


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:


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



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!