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.
for i in 0..5 { println!("{i}"); } for (i, name) in names.iter().enumerate() { println!("{i}: {name}"); }
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 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 &vkeepsv;for x in vconsumes it;for x in v.iter_mut()or&mut vallows edits. - Arrays by value (
for x in [1, 2, 3]) yield owned items since edition 2021, not references. - Ranges
a..bexcludeb,a..=binclude 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/chunkson 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
retainor indexes. - HashMap order is unspecified. Sort the keys if output must be deterministic.
forversus iterator methods: useforwhen the body has side effects or early exits; usemap/filter/sumwhen you are building a value.- Labels let
break 'outerandcontinue 'outeract on enclosing loops.
Related
while,loop,breakandcontinue,in, Range types- Lessons: Loops, Iterators, Custom iterators