Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The for loop

Reference for Rust for loops: iterating ranges and collections, the IntoIterator desugaring, borrowing versus consuming, patterns, enumerate and labels.

for pattern in expression { body } runs the body once per item produced by an iterator. The expression can be anything that implements IntoIterator: ranges, vectors, arrays, slices, maps, strings' iterators, and your own types. The loop variable is a pattern, so tuples and structs can be unpacked right in the header.

Whether items are moved out, borrowed or mutably borrowed depends on what you iterate: for x in v consumes the vector, for x in &v yields &T, and for x in &mut v yields &mut T. A for loop cannot go out of bounds and is typically as fast as manual indexing, because bounds checks can be optimized away.

Rust
for i in 0..5 { println!("{i}"); }
for (i, name) in names.iter().enumerate() { println!("{i}: {name}"); }

Try it

Rust Ranges and collections

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 Patterns, zip and your own IntoIterator

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
for PATTERN in EXPRESSION { body }
'label: for PATTERN in EXPRESSION { ... }

// desugars to roughly:
let mut it = IntoIterator::into_iter(EXPRESSION);
while let Some(PATTERN) = it.next() { body }
Part Description
PATTERN Must be irrefutable: x, (a, b), &n, Point { x, y }, _.
EXPRESSION Evaluated once and converted with IntoIterator::into_iter.
body Runs per item. break and continue work as in other loops; break cannot carry a value.

Compile error: after for x in v moves v, using v again is E0382, "borrow of moved value". Run time: the loop itself never panics; a panic can only come from the body.

Usage notes

  • Choose the borrow form on purpose. for x in &v keeps v; for x in v consumes it; for x in v.iter_mut() or &mut v allows edits.
  • Arrays by value (for x in [1, 2, 3]) yield owned items since edition 2021, not references.
  • Ranges a..b exclude b, a..=b include it. An empty range (5..3) simply runs zero times. Reverse with .rev(); counting down by hand with unsigned types easily underflows.
  • Adapters make loops expressive: enumerate, zip, skip, take, chain, windows/chunks on slices; see Iterators.
  • Do not mutate the collection you iterate. The borrow checker forbids pushing to a vector while looping over it; collect changes first, or use retain or indexes.
  • HashMap order is unspecified. Sort the keys if output must be deterministic.
  • for versus iterator methods: use for when the body has side effects or early exits; use map/filter/sum when you are building a value.
  • Labels let break 'outer and continue 'outer act on enclosing loops.