Sometimes it is worthwhile to think deeply on, or reflect upon, functions you use often in a language. Consider iter
and into_iter
in Rust. These create iterators and then we can loop over elements in a for
-loop.
As I wrote in my article about this subject, iter
returns references, and into_iter
returns the original values. But the key difference between iter
and into_iter
is not the return values—it is that into_iter
consumes the variable—it is "moved" to the iterator's ownership. Iter
meanwhile just acts upon a reference of the original variable.
This means that:
Into_iter
can return the original values in the collection, as it has ownership of them.Into_iter
will cause a variable to be unavailable for later use in a function.Iter
can be called in multiple places in a function without any moved value errors.The important thing is that into_iter
takes ownership of the collection, and iter
does not. In Rust, the for
-loop on a collection implicitly calls into_iter
—for beginners, changing this to iter
can eliminate moved value errors.