Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Rust While Loops


The while Loop

The while loop runs as long as a condition is true.

Example

let mut count = 1;

while count <= 5 {
  println!("Count: {}", count);
  count += 1;
}
Try it Yourself »

In the example above, the loop keeps running as long as the counter is less than or equal to 5.

It prints the numbers from 1 to 5, one on each line.


False Condition

The while loop checks the condition before each loop, so if the condition is false at the start, the loop will not run at all:

Example

let count = 10;

while count <= 5 {
  println!("This won't be printed.");
}

Stop a While Loop

You can stop a while loop when you want by using break:

Example

let mut num = 1;

while num <= 10 {
  if num == 6 {
    break;
  }
  println!("Number: {}", num);
  num += 1;
}
Try it Yourself »

This prints numbers from 1 to 5 (stops the loop when num reaches 6).

Next: Learn how to use the for loop to go through a range of values.


Skip a Value

You can skip a value by using the continue statement:

Example

let mut num = 1;

while num <= 10 {
  if num == 6 {
    num += 1;
    continue;
  }

  println!("Number: {}", num);
  num += 1;
}
Try it Yourself »

This prints numbers from 1 to 10, except for the number 6.

Next: Learn how to use the for loop to go through a range of values.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.