Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator by_ref, iter, iter_mut and into_iter

Reference for borrowing and consuming iterators in Rust: by_ref to reuse an iterator, iter versus iter_mut versus into_iter, and for-loop desugaring.

Most iterator methods take self by value, which means they consume the iterator. by_ref() hands out a &mut reference to it instead, and a mutable reference to an iterator is itself an iterator. You can therefore run an adapter such as take on part of a stream and keep using the original afterwards.

The other half of this page is the trio that creates iterators from collections: iter() borrows items, iter_mut() borrows them mutably and into_iter() consumes the collection and yields owned items.

Rust
let mut it = 1..10;
let first: Vec<_> = it.by_ref().take(3).collect(); // [1, 2, 3]
let rest: Vec<_> = it.collect();                    // [4, 5, 6, 7, 8, 9]

Try it

Rust Using by_ref to split a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust iter versus iter_mut versus into_iter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn by_ref(&mut self) -> &mut Self where Self: Sized;

// Provided by collections:
fn iter(&self) -> Iter<'_, T>;          // items are &T
fn iter_mut(&mut self) -> IterMut<'_, T>; // items are &mut T
fn into_iter(self) -> IntoIter<T>;      // items are T (IntoIterator::into_iter)
Name Description
by_ref() Borrow an iterator mutably so that adapters do not take ownership of it.
iter() Iterate by shared reference. The collection remains usable afterwards.
iter_mut() Iterate by mutable reference; you can modify items but not add or remove elements.
into_iter() Consume the collection and yield owned items.

Returns: &mut Self (itself an Iterator) for by_ref; the item types listed above for the others.

Errors / panics / edge cases: using a collection after into_iter() is a compile error (use of moved value). Holding iter() while calling a &mut self method on the same collection is rejected by the borrow checker. No runtime panics.

Usage notes

  • for x in v, for x in &v and for x in &mut v call into_iter() on Vec<T>, &Vec<T> and &mut Vec<T> respectively. This is why the three forms give owned, shared and mutable items.
  • by_ref is just &mut self. The same effect is possible with (&mut it).take(3). The iterator state moves forward as the adapter consumes items, and anything the adapter reads ahead is lost: take_while swallows the first failing item, as the example shows.
  • Partial consumption: by_ref().take(n) is the idiomatic way to read a fixed prefix, then continue with the remainder; skip plus take on a fresh iterator would walk the data twice.
  • Arrays: in editions 2021 and later array.into_iter() yields values. In 2018, it yielded references. Our runner uses edition 2024.
  • Maps: HashMap::iter() yields (&K, &V); iter_mut() yields (&K, &mut V); keys are never mutable.
  • into_iter on a reference ((&v).into_iter()) is the same as v.iter(); method-call syntax on a Vec binding picks the by-value form.
  • Performance: all of them are zero-cost wrappers around pointers; into_iter on a Vec reuses the allocation when collected into another Vec of a same-sized type.