The for Loop
The for loop is used to traverse collections such as arrays, vectors, ranges, or any type that implements the Iterator trait. Its fundamental syntax is:Iterating Over an Array
In the following example, the for loop iterates through an array of numbers and prints each one:Iterating Over a Range
You can also use the for loop to iterate over a range. Note that the upper bound is exclusive. This example iterates from 1 to 5 (since 6 is excluded):The while Loop
The while loop repeatedly executes a block of code as long as a specified condition remains true. Its syntax is:Basic while Loop Example
Consider this example where the loop continues until the variablenumber reaches 0:
number is decremented to 0, the condition becomes false and the loop terminates, printing “Liftoff!”.
Combining Multiple Conditions
You can use logical operators to create more complex loop conditions. The following example demonstrates a while loop that runs as long asnumber is less than limit and even. The number is printed and incremented by 2 on each iteration:
Using break and continue
Rust offers thebreak and continue statements to control loop flow more precisely. Use break to exit a loop early and continue to skip the rest of the current iteration.
Using break and continue in a for Loop
The example below demonstrates a for loop that breaks when the number is 5 and skips even numbers:Using break and continue in a while Loop
The logic for break and continue can be similarly applied within a while loop. In the following example, the variablenum is initialized to 0 and updated in each iteration:
Summary
Understanding and effectively using for and while loops in Rust provides you with the control-flow mechanisms necessary to write efficient, readable programs. In this guide, we covered:- The for loop for iterating over collections such as arrays, vectors, and ranges.
- The while loop for repeating code blocks based on dynamic conditions.
- Combining logical conditions within while loops for advanced looping behavior.
- The use of
breakto terminate loops early andcontinueto skip to the next iteration.

Mastering these loop constructs in Rust not only enhances the clarity of your code but also ensures higher efficiency when processing collections.