Rust provides three main types of loops for iterating over blocks of code:
loop: Infinite Loopswhile: Conditional Loopsfor: Iterative Loops
Each loop type serves different use cases and offers flexibility in controlling flow.
1. loop: Infinite Loops
The loop keyword creates an infinite loop that runs until explicitly terminated using a break statement.
Example:
Key Features:
- Runs indefinitely unless a
breakcondition is provided. - Commonly used when the number of iterations is unknown.
- Can return values using
break.
Returning Values from loop:
2. while: Conditional Loops
The while loop continues running as long as a specified condition evaluates to true.
Example:
Key Features:
- Executes zero or more times depending on the condition.
- Suitable for cases where the iteration depends on dynamic conditions.
3. for: Iterative Loops
The for loop is used for iterating over collections, ranges, or iterators. It is the most commonly used loop in Rust due to its safety and flexibility.
Example 1: Iterating Over a Range
Output:
Example 2: Inclusive Ranges
Example 3: Iterating Over a Collection
Example 4: Using Enumerate
Summary of Loop Types
| Type | Use Case | Key Features |
|---|---|---|
loop | Infinite looping, run until explicitly stopped | Requires break to exit, can return values. |
while | Looping based on a condition | Executes while a condition is true. |
for | Iterating over ranges, collections, or iterators | Safe, concise, and commonly used for iterations. |
Breaking and Continuing in Loops
break: Terminates the loop.continue: Skips the rest of the current iteration and moves to the next.
Example:
Output:

Comments
Post a Comment