Basic

Loops

Repeat work with loop, while, and for.

What you will see

[2, 4, 6]

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

You will repeat work with loop, while, and for, and use iterators to transform data.

1

I run an infinite loop that breaks once the counter exceeds five. The final value prints after the loop ends.

fn main() { let mut count = 0; loop { count += 1; if count > 5 { break; } } println!("{}", count); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
6
2

I count down with a while loop. The condition is checked before each iteration, so it prints three, two, one.

fn main() { let mut n = 3; while n > 0 { println!("{}", n); n -= 1; } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 2 1
3

I iterate a half-open range. for prints each value from the start up to but not including the end.

fn main() { for i in 0..3 { println!("{}", i); } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0 1 2
4

I use break with a value inside a loop. That value becomes the result of the whole loop expression.

fn main() { let result = loop { break 42; }; println!("{}", result); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
42
5

I build a vector and map each element. The map transforms every item, and collect gathers them into the new vector.

fn main() { let nums = vec![1, 2, 3]; let doubled: Vec = nums.iter().map(|n| n * 2).collect(); println!("{:?}", doubled); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
[2, 4, 6]

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A loop repeats a block; iterators transform each element lazily.
1 Initialize the loop or iterator
↓
2 Check the condition
↓
3 Execute the body
↓
4 Advance and repeat until done
Why this works
Loop as expression

In Rust, loop can return a value:

let x = loop {
    break 10;
};

The break 10 sets the loop's result to 10. This replaces the need for a separate result variable in many counting patterns.

Iterators

Iterators transform data lazily:

let nums = vec![1, 2, 3];
let doubled: Vec<i32> = nums.iter().map(|n| n * 2).collect();

map transforms each item; collect gathers results. Iterators are lazy, nothing runs until you call collect or another consuming method.

Examples

The loop keyword

Infinite loops

let mut count = 0;
loop {
    count += 1;
    if count > 5 {
        break;
    }
}

loop runs forever until break. You can return a value from break:

let result = loop {
    break 42;
};

Why it works: break with a value makes loop an expression.

While loops

Counting loops

let mut n = 3;
while n > 0 {
    println!("{n}");
    n -= 1;
}

while runs while a condition is true. The condition is checked before each iteration. Use it when the count is not known in advance.

For over ranges

Iterating

for i in 0..5 {
    println!("{i}");
}
for fruit in ["a", "b", "c"] {
    println!("{fruit}");
}

for iterates over ranges and iterators. 0..5 is half-open (0 to 4); 0..=5 includes the end. Rust for loops are safe, no off-by-one panics.

Why it works: the iterator owns the loop bounds.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Conditionals and Matching
Previous Lesson
Conditionals and Matching
Next Lesson
Functions
Functions →