Rust Control Flow
Estimated reading: 3 minutes 279 views

🦀 Rust – While Loops: Conditional Repetition with Safe Control

Introduction – Why Learn while Loops in Rust?

In Rust, the while loop lets you repeat a block of code as long as a condition is true. It’s ideal when you don’t know the exact number of iterations in advance. Rust’s strict type system ensures your loop logic is safe, explicit, and error-resistant.

In this guide, you’ll learn:

  • How to use while loops effectively
  • Compare while vs. loop and for
  • Use break, continue, and nested loops
  • Examples with output and line-by-line explanation

Basic while Loop

Code Example:

fn main() {
    let mut count = 3;

    while count > 0 {
        println!("Counting down: {}", count);
        count -= 1;
    }

    println!("Liftoff!");
}

Explanation:

  • let mut count = 3; → A mutable counter starts at 3.
  • while count > 0 → Condition is checked before each iteration.
  • count -= 1; → Reduces count by 1 on every loop.

Output:

Counting down: 3
Counting down: 2
Counting down: 1
Liftoff!

Looping Until a Condition is Met

Code Example:

fn main() {
    let mut num = 1;

    while num * num < 100 {
        println!("num: {}, square: {}", num, num * num);
        num += 1;
    }
}

Explanation:

  • Loops until num * num >= 100.
  • Each iteration increases num.

Output (first few lines):

num: 1, square: 1
num: 2, square: 4
num: 3, square: 9
...
num: 9, square: 81

Using continue to Skip Iterations

Code Example:

fn main() {
    let mut i = 0;

    while i < 5 {
        i += 1;

        if i % 2 == 0 {
            continue; // skip even numbers
        }

        println!("Odd number: {}", i);
    }
}

Explanation:

  • i += 1; is placed before the condition to avoid infinite loop.
  • continue skips printing when i is even.

Output:

Odd number: 1
Odd number: 3
Odd number: 5

Using break to Exit Early

Code Example:

fn main() {
    let mut attempts = 0;

    while attempts < 10 {
        println!("Attempt: {}", attempts);
        if attempts == 3 {
            break;
        }
        attempts += 1;
    }
}

Explanation:

  • Loop exits when attempts == 3.

Output:

Attempt: 0
Attempt: 1
Attempt: 2
Attempt: 3

Nested while Loops

Code Example:

fn main() {
    let mut outer = 1;

    while outer <= 2 {
        let mut inner = 1;

        while inner <= 3 {
            print!("({},{}) ", outer, inner);
            inner += 1;
        }

        println!();
        outer += 1;
    }
}

Explanation:

  • A while loop inside another—prints coordinate pairs.

Output:

(1,1) (1,2) (1,3) 
(2,1) (2,2) (2,3) 

Common Mistakes with while Loops

MistakeProblemFix
Forgetting mut for variable“cannot assign twice to immutable”Use let mut variable = value
Infinite loopMissing update to loop variableEnsure loop condition eventually fails
Misplaced continue or breakMay skip increment or exit too earlyStructure control statements properly

Summary – Recap & Next Steps

Rust’s while loop is ideal for conditional repetition. It gives you precise control while avoiding common mistakes like off-by-one errors and infinite loops—thanks to Rust’s compiler checks.

Key Takeaways:

  • Use while when loop count is not predetermined
  • Loop condition is checked before each iteration
  • Use continue to skip and break to exit
  • Use nested loops for grid-like control

Next up: Dive into Rust – For Loops for range-based and iterator-based looping.


FAQs


When should I use a while loop in Rust?
Use while when the number of iterations is unknown and based on a condition, such as reading from a file or waiting for input.


What happens if the loop condition never becomes false?
You’ll create an infinite loop. Rust won’t stop it unless you break manually or the condition eventually fails.


Can I return a value from a while loop?
No. Unlike loop, a while loop cannot return a value directly via break value;.


Does Rust support do…while loops?
No. Rust does not have a built-in do…while. You can simulate it using loop with manual condition checks.


Share Now :
Share

Rust – While Loops

Or Copy Link

CONTENTS
Scroll to Top