Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. loop / while / for

loop / while / for

Rust has three loop constructs: loop, while, and for. loop creates an infinite loop that can return a value, and for is used together with iterators.

Syntax

// Infinite loop. You can return a value with break.
let result = loop {
    // ...
    break 42;  // 42 is assigned to result.
};

// Loops while the condition is true.
while condition {
    // ...
}

// Iterates over an iterator (most commonly used).
for x in 0..5 {          // 0, 1, 2, 3, 4
    // ...
}
for x in 0..=5 {         // 0, 1, 2, 3, 4, 5 (inclusive end)
    // ...
}
for item in &vec {        // Borrows each element of the slice.
    // ...
}

// Control loop execution.
break;     // Exits the loop.
continue;  // Skips to the next iteration.

Syntax List

SyntaxDescription
loop { }Infinite loop. You can return a value with break.
while condition { }Loops while the condition is true.
while let Some(x) = opt.pop() { }Loops while the pattern match succeeds.
for x in iterator { }Iterates over each element of an iterator.
0..nA range from 0 up to (but not including) n.
0..=nA range from 0 up to and including n.
breakExits the loop. In a loop, break value; returns a value.
continueSkips the remaining code and moves to the next iteration.
'label: loop { }A labeled loop. Use break 'label; to break out of an outer loop.

Sample Code

fn main() {
    // loop: infinite loop that returns a value via break.
    let mut count = 0;
    let result = loop {
        count += 1;
        if count == 5 {
            break count * 2;  // The break value is assigned to result.
        }
    };
    println!("loop result: {}", result);  // 10

    // while: conditional loop example.
    let mut n = 1;
    while n < 32 {
        print!("{} ", n);
        n *= 2;
    }
    println!();  // 1 2 4 8 16

    // while let: loops while the Option is Some.
    let mut stack = vec![1, 2, 3];
    while let Some(top) = stack.pop() {
        print!("{} ", top);  // 3 2 1
    }
    println!();

    // for + range: 0..5 covers 0 through 4.
    print!("0..5: ");
    for i in 0..5 {
        print!("{} ", i);
    }
    println!();

    // for + inclusive range: 0..=5 covers 0 through 5.
    print!("0..=5: ");
    for i in 0..=5 {
        print!("{} ", i);
    }
    println!();

    // for + borrowed slice.
    let fruits = ["apple", "banana", "cherry"];
    for fruit in &fruits {
        println!("fruit: {}", fruit);
    }

    // Use enumerate to get both the index and the value.
    for (i, fruit) in fruits.iter().enumerate() {
        println!("  [{}] {}", i, fruit);
    }

    // Use a labeled loop to break out of nested loops.
    'outer: for x in 0..3 {
        for y in 0..3 {
            if x == 1 && y == 1 {
                println!("Breaking outer loop at ({},{})", x, y);
                break 'outer;
            }
            print!("({},{}) ", x, y);
        }
    }
    println!();
}

Notes

In Rust, the for loop works closely with the iterator protocol. When iterating over a slice or array by reference, make sure to use & — omitting it moves ownership into the loop.

loop is equivalent to while true in other languages, but with the ability to return a value. When you need to exit a loop based on a condition variable, loop with break is often more idiomatic Rust than while.

Rust has no C-style for(int i=0; i<n; i++). Use for i in 0..n instead.

For conditional branching, see 'if / else / if let'. For pattern matching, see 'match / Pattern Matching'.

If you find any errors or copyright issues, please .