Home > database >  What is the mechanism behind a `for` loop?
What is the mechanism behind a `for` loop?

Time:08-30

The rust language reference seems to describe the desugaring of for loops in terms of calling IntoIterator::into_iter on the expression provided after the in keyword in order to obtain an Iterator, then use that Iterator to retrieve the elements to loop over.

However, in practice the for loop seems to work just fine with expressions of either IntoIterator or Iterator:

let v = vec!(1, 2, 3);

// Either of these work:
for i in v { ... }               // v             impl IntoIterator
for i in v.into_iter() { ... }   // v.into_iter() impl Iterator

So the acutal rule seems to be: If the expression is already an Iterator, loop over that, otherwise, call into_iter on the expression to the get an Iterator to loop over. However, thats not what the documentation is saying.

So what am I missing? Is the documentation incomplete? Is there some magic going on with the IntoIterator::into_iter call? Or do Iterators also implement IntoIterator to make it work? Or did I completely misunderstand how it works?

CodePudding user response:

There is a blanket implementation of IntoIterator for types implementing Iterator, that returns the iterator itself. Thus, if you take IntoIterator you can work with Iterators too.

  • Related