Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 132 ยท Operators and Control Flow

loop, while and for

Learn Rust loops - loop with break values, while, while let, for over ranges and iterators, continue, labeled breaks, step_by, rev and why for beats index loops.

A loop repeats code. Rust has three kinds: loop (repeat forever until you say stop), while (repeat while a condition holds) and for (visit every item of something). If you come from C, Java or JavaScript, you will notice what is missing: there is no C-style for (int i = 0; i < n; i++), no do ... while, and no ++. Rust replaces them with a smaller set of tools that are harder to get wrong.

This lesson covers each loop, how break and continue work (including break with a value and labels for nested loops), how to count with ranges, and why for over an iterator is the loop you will use most. Loops come after match in this chapter, and the next lesson, Patterns in Depth, shows what for and while let really accept on their left side.

loop: repeat until you break

loop has no condition. It runs its body again and again until something stops it, usually break:

Rust loop and break

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.

Use loop when the exit condition is in the middle of the body, when there are several exits, or when the loop is meant to run for the whole life of the program (a server waiting for requests, for example).

Returning a value from a loop

loop is an expression, and break can carry a value that becomes the value of the whole loop. That is something while and for cannot do:

Rust break with a value

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.

Notice the semicolon after the closing brace: the whole loop { ... } is the right side of a let. Because loop can only end through a break, the compiler knows the value is always produced, so there is no "what if the loop never ended" case to handle.

while: repeat while a condition is true

while checks a condition before every round, and stops when it is false. The condition must be a real bool; Rust never treats 0 or an empty string as false:

Rust A while loop: the Collatz sequence

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.

Use while when you do not know in advance how many rounds are needed but the stopping rule is a simple condition. Because Rust has no do ... while, code that must run at least once is written as a loop with a break at the end, or you simply run the body once before the while.

while let: loop as long as a pattern matches

while let repeats as long as a pattern matches. It is perfect for draining something that eventually runs out, like a stack:

Rust while let with pop

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.

Vec::pop returns Some(value) while there are elements and None when the vector is empty. The loop runs while the answer is Some(top) and stops at None, with no index and no length check. This reads the same way the Option lesson describes the type.

for: visit every item

for is the workhorse. It takes anything that can turn into an iterator, a thing that hands out one item at a time, and runs the body once per item:

Rust for over ranges

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.

The syntax a..b is a range that includes a and excludes b; a..=b includes both ends. A range is an ordinary value, an iterator that counts. This also explains why there is no C-style for: you describe what to visit rather than managing a counter by hand.

Looping over collections

The same for visits the items of arrays, vectors and other collections. What matters is how you hand the collection over:

Rust for over a vector: borrow, mutate, consume

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.

  • for x in &v gives &T references and leaves v usable afterwards.
  • for x in &mut v gives &mut T references; you write *x to change the value.
  • for x in v moves the vector into the loop and gives you owned T values. After the loop v is gone. This is ownership at work, and a common cause of "borrow of moved value" errors:
Rust Using a vector after a for loop consumed it (fails on purpose)

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.

The compiler stops you with error[E0382]: borrow of moved value: 'names' and points at the for line with a note that names was moved because into_iter takes ownership. The fix is to write for name in &names.

Counting with the index

When you need the position as well as the item, do not write for i in 0..v.len() and index into the vector. Ask the iterator to number the items with .enumerate():

Rust enumerate gives index and item

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.

The (index, planet) on the left is a tuple pattern, the first example of a pattern in a for header. Besides being shorter, this version cannot go out of bounds. An index loop v[i] checks the index on every access at run time and can panic; an iterator knows it stays inside the collection, so the check is not needed and the loop is usually just as fast, often faster.

Prefer iterating over items to indexing with a counter. Reach for 0..len only when the index itself is the point, such as comparing v[i] with v[i + 1]. For that case, v.windows(2) is often even better; see the Iterators lesson.

step_by and rev

Ranges are iterators, so they come with adapters that change how they count:

Rust step_by and rev

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.

The parentheses are needed because method calls bind tighter than ..; without them 0..=12.step_by(3) would try to call step_by on the number 12. A descending range such as 5..1 is simply empty: Rust does not count backwards on its own, so use .rev().

break, continue and labels

break leaves the loop; continue skips the rest of the current round and goes to the next one. Both apply to the innermost loop:

Rust continue and break

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.

With nested loops you sometimes want to leave the outer loop from inside the inner one. Give the outer loop a label, a name starting with a single quote, and say which loop to break or continue:

Rust Labeled loops

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.

Without the label, break would only leave the inner loop and the search would carry on through the remaining rows. Labels also work with continue 'rows, and since Rust 1.65 a label can be put on a plain block so you can break 'name value out of it early.

Only loop may break with a value. In a for or while the loop might never run, so there would be no value to return. The usual workaround is a variable declared before the loop, as found above.

Which loop should I use?

Situation Use
Visit every item of a collection or range for
Repeat while a simple condition holds while
Take items until a pattern stops matching (pop, recv, next) while let
Retry until success, or an exit in the middle, or return a value loop

If you can write the job as a for, do. It states the intent, cannot run off the end, and gives the optimizer the most to work with. Complex loops that filter, transform and sum are often better as an iterator chain (.iter().filter(...).sum()), which you meet in Iterators.

Common mistakes

  • Expecting i++. Rust has no increment operator; write i += 1.
  • Off-by-one with ranges. 0..n runs n times with the values 0 to n - 1. Use ..= if you want the end included.
  • Mutating a collection while iterating over it. for x in &v { v.push(*x); } does not compile, because the loop holds a shared borrow of v and push needs a mutable one. This is the borrowing rule protecting you from an invalidated iterator.
  • Infinite while true. Rust warns you: write loop instead. The compiler also understands that loop never ends without break.
  • Subtraction on usize below zero. for i in (0..n - 1) panics in a debug build when n is 0 because n - 1 overflows. Prefer for i in 1..n or saturating_sub.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which loop can return a value with break value?

    Only loop is guaranteed to run until a break executes, so only loop can produce a value. for and while might run zero times.
  2. 2. What does for i in 1..5 print?

    a..b excludes the end. Use 1..=5 to include 5.
  3. 3. What happens to names after for name in names { ... } when names is a Vec<String>?

    for x in v calls into_iter on the vector, which takes ownership. Use &names to keep it.
  4. 4. How do you stop an outer loop from inside an inner loop?

    Name the outer loop with a label such as 'rows: and write break 'rows. A plain break only leaves the innermost loop.
  5. 5. Which of these is the idiomatic way to walk through a slice while knowing each position?

    enumerate pairs each item with its index, avoids repeated bounds checks and cannot go out of range.

Summary

  • loop repeats until break; it is an expression, and break value returns a value from it.
  • while condition checks a real bool before each round; while let repeats while a pattern matches (for example Some(x) = stack.pop()).
  • for item in iterable visits each item; ranges are a..b (end excluded) and a..=b (end included).
  • for x in &v borrows, &mut v borrows mutably, v moves the collection into the loop.
  • Use .enumerate(), .rev() and .step_by(n) instead of manual counters.
  • continue skips to the next round; break leaves the innermost loop; labels like 'outer: let you exit an outer one.
  • There is no ++, no C-style for and no do ... while.

Next: Patterns in Depth