Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The in keyword

Reference for Rust in: how for pattern in iterable works, what it expands to, ranges and by-reference iteration, and the pub(in path) visibility form.

in separates the pattern from the iterable in a for loop: for pattern in expression { ... }. The expression is converted with IntoIterator::into_iter, and the loop calls next() until it returns None. That is why a for loop works with ranges, vectors, maps, strings' chars() and your own iterators.

in has one other use: pub(in path), which restricts an item's visibility to a given ancestor module. Outside for loops and visibility modifiers it is not valid.

Rust
for n in 1..=3 {
    println!("{n}");
}

Try it

Rust What you can put after in

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 The loop desugared

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 iterable { body }
'label: for pattern in iterable { body }
pub(in crate::module) fn helper() {}
Part Description
pattern Any irrefutable pattern: a name, _, a tuple, a struct pattern. A refutable pattern (like Some(x)) is a compile error.
iterable Any type implementing IntoIterator. The loop evaluates it once.
pub(in path) Makes the item visible inside path, which must be an ancestor of the current module.

Usage notes

  • for x in v consumes v (vectors, maps, strings). Use &v or &mut v, or v.iter(), to keep it.
  • A for loop is an expression of type (). You cannot break with a value from it (only from loop); use find or position on an iterator for that.
  • Ranges are half-open: 0..n excludes n, 0..=n includes it. Reverse with (0..n).rev(), step with .step_by(k).
  • Modifying a collection while iterating over it by reference is rejected by the borrow checker.
  • Labels let break 'outer and continue 'outer act on an enclosing loop.
  • Performance: for over a range or slice compiles to a tight loop; bounds checks are usually removed when iterating directly rather than indexing.
  • while let Some(x) = iter.next() is the manual form when you need to touch the iterator inside the loop.