Rust Tutorial · Rust Basics · Lesson 7 of 29

Rust Control Flow

Branch with if and match, and repeat with loop, while and for over ranges and collections.

Create a free account to save this page, take notes and track your progress. Sign in

Loops

  • loop repeats until break (and can return a value: break value).
  • while condition { ... }
  • for item in collection { ... } and ranges: 0..5 (exclusive), 1..=5 (inclusive).
for, while and loop
fn main() {
    for i in 1..=3 {
        println!("attempt {i}");
    }
    let mut countdown = 3;
    while countdown > 0 {
        print!("{countdown}.. ");
        countdown -= 1;
    }
    println!("go");
    let mut n = 1;
    let first_over_100 = loop {
        n *= 3;
        if n > 100 { break n; }
    };
    println!("first power of 3 over 100: {first_over_100}");
    for (index, fruit) in ["apple", "pear"].iter().enumerate() {
        println!("{index}: {fruit}");
    }
}

Output

attempt 1
attempt 2
attempt 3
3.. 2.. 1.. go
first power of 3 over 100: 243
0: apple
1: pear

Run this on your computer — see “Get Started” for setup.

Labelled breaks

Name an outer loop to break out of nested loops: 'outer: for ... { break 'outer; }.

Test yourself

What does 1..=5 produce in a for loop?

  1. 1, 2, 3, 4
  2. 1, 2, 3, 4, 5
  3. 0 to 5
  4. 5 to 1
Show answer

Answer: 1, 2, 3, 4, 5

Was this page helpful?