liveBook · Manning

Loop

As explained in Learn Rust in a Month of Lunches

A for loop is Rust iteration syntax that repeatedly executes a block for each item produced by an iterable value.

A for loop repeats a block for each item in a range or other iterable value. Unlike a while loop, it stops after the range is exhausted instead of repeatedly checking a condition. section 3.2.3

fn main() {
    for number in 0..3 {
        println!("The number is: {}", number);
    }
 
    for number in 0..=3 {
        println!("The next number is: {}", number);
    }
}

Use a variable such as number to receive each value from a range. The range 0..3 excludes 3, while 0..=3 includes it. section 3.2.3

Choose the loop form that matches the job:

  • Use a for loop when you want to perform an action for every value in a known range. section 3.2.3
  • Use _ when each iteration needs no item value; Rust avoids creating an unused-variable warning. section 3.2.3
  • Use a named variable when the body needs the current item; Rust warns if that variable is never used. section 3.2.3
  • Use while or loop when repetition depends on a condition or an explicit break rather than a range. section 3.2.3
fn main() {
    for _ in 0..3 {
        println!("Printing the same thing three times");
    }
}

This version repeats the same statement three times without using the range item. section 3.2.3

Processing items from a collection

A for loop can also unpack each item while it iterates. For example, looping over color-and-amount pairs lets the body compare each amount and report colors below 10. section 3.2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains syntax, inclusive and exclusive ranges, unused variables, and tuple patterns without descending into iteration internals.
Examples
Demonstrates numeric ranges, ignored values, unused-variable warnings, tuple destructuring, and vector indexing.
What it assumes
Assumes basic variables and ranges, while introducing loop choice and the underscore pattern through examples.
What you can do after
Apply via Rust syntax to repeat work over ranges or collection items and respond appropriately to compiler warnings.
How it connects
Connects for loops with ranges, variables, while loops, loop expressions, tuples, and pattern matching.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.