Home
Blog
Understanding iter and into_iter in Rust
Updated
Dot Net Perls

Understanding iter and into_iter in Rust

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.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen