Basics

Rust Loops

Loop Structures

Rust loops use loop for and while with break and continue.

Introduction to Loops in Rust

Loops in Rust are essential for executing a block of code repeatedly. Rust provides three primary looping constructs:

  • loop - An infinite loop that runs until explicitly stopped.
  • for - Iterates over a collection or range.
  • while - Repeats while a condition is true.

Additional control over loops can be achieved using break and continue statements.

Using the loop Keyword

The loop keyword in Rust provides a way to create an infinite loop. It will continue to execute until you explicitly break out of it using the break statement. This can be useful for scenarios where you want to wait for an external condition to stop the loop.

Iterating with for Loops

The for loop in Rust is ideal for iterating over a range or a collection. It provides a clean and concise syntax for handling iterations.

Conditional Execution with while Loops

The while loop executes as long as a specified condition is true. It is particularly useful when the number of iterations is not known in advance, and you need to loop until a condition changes.

Controlling Loop Flow with break and continue

Rust provides the break and continue statements to control the flow of loops:

  • break - Exits the loop entirely.
  • continue - Skips the rest of the current iteration and moves to the next iteration.
Previous
Match