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.
for n in 1..=3 { println!("{n}"); }
Try it
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.
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
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 vconsumesv(vectors, maps, strings). Use&vor&mut v, orv.iter(), to keep it.- A
forloop is an expression of type(). You cannotbreakwith a value from it (only fromloop); usefindorpositionon an iterator for that. - Ranges are half-open:
0..nexcludesn,0..=nincludes 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 'outerandcontinue 'outeract on an enclosing loop. - Performance:
forover 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.
Related
for,loop,breakandcontinue,pub, Range types- Lessons: Loops, Iterators, Modules