Rust provides three main types of loops for iterating over blocks of code:

  1. loop: Infinite Loops
  2. while: Conditional Loops
  3. for: 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:

fn main() { let mut counter = 0; loop { counter += 1; println!("Counter: {}", counter); if counter == 5 { break; // Exit the loop } } println!("Exited the loop"); }

Key Features:

  • Runs indefinitely unless a break condition is provided.
  • Commonly used when the number of iterations is unknown.
  • Can return values using break.

Returning Values from loop:

fn main() { let result = loop { let x = 10; break x * 2; // Returns a value and exits the loop }; println!("Result: {}", result); }

2. while: Conditional Loops

The while loop continues running as long as a specified condition evaluates to true.

Example:

fn main() { let mut number = 3; while number > 0 { println!("Number: {}", number); number -= 1; // Decrement the counter } println!("Done!"); }

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

fn main() { for i in 1..5 { // Ranges are exclusive of the upper bound println!("i: {}", i); } }

Output:

i: 1 i: 2 i: 3 i: 4

Example 2: Inclusive Ranges

fn main() { for i in 1..=5 { // Inclusive range (includes 5) println!("i: {}", i); } }

Example 3: Iterating Over a Collection

fn main() { let array = [10, 20, 30, 40, 50]; for value in array.iter() { println!("Value: {}", value); } }

Example 4: Using Enumerate

fn main() { let array = ["a", "b", "c"]; for (index, value) in array.iter().enumerate() { println!("Index: {}, Value: {}", index, value); } }

Summary of Loop Types

TypeUse CaseKey Features
loopInfinite looping, run until explicitly stoppedRequires break to exit, can return values.
whileLooping based on a conditionExecutes while a condition is true.
forIterating over ranges, collections, or iteratorsSafe, 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:

fn main() { for i in 1..10 { if i % 2 == 0 { continue; // Skip even numbers } if i == 7 { break; // Exit the loop when i is 7 } println!("i: {}", i); } }

Output:

i: 1 i: 3 i: 5

Comments

Popular posts from this blog