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 Loops


Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable. For example, instead of writing the same line 10 times to print some text, you can use a loop to repeat it for you.

Rust has three types of loops: loop, while, and for.


loop

loop is the simplest of Rust's three loop types.

It will run forever unless you tell it to stop:

loop {
  println!("This will repeat forever!");
}

Warning: This loop never stops! You will need to press Ctrl + C to end the program.

To stop a loop, use the break keyword:

Example

let mut count = 1;

loop {
  println!("Hello World!");

  if count == 3 {
    break;
  }

  count += 1;
}
Try it Yourself »

Example explained:

  • This prints "Hello World!" 3 times.
  • It uses a counter to keep track of how many times it has looped.
  • The counter starts at 1 (let mut count = 1;).
  • Each time the loop runs, the counter goes up by 1: (count += 1;).
  • When it reaches 3, the loop stops.

Return a Value

You can also return a value from a loop using break with a value.

This lets you save the result of the loop into a variable:

Example

let mut count = 1;

let result = loop {
  println!("Hello!");

  if count == 3 {
    break count; // Stop the loop and return the number 3
  }

  count += 1;
};

println!("The loop stopped at: {}", result);
Try it Yourself »

This loop prints "Hello!" until count reaches 3, then stops and returns that number.

Note: When you save the result of a loop into a variable, you must put a semicolon (;) at the end.

Next: Learn how to use while loops to repeat code while a condition is true.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

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.