DEV Community

Cover image for Day 6: Navigating Rust's Looping Landscape
Aniket Botre
Aniket Botre

Posted on

Day 6: Navigating Rust's Looping Landscape

Greetings, fellow coders! πŸš€ On Day 6 of my #100DaysOfCode adventure with Rust, I explored the rhythmic world of loops – a crucial construct for repetitive tasks. Let's unravel the three types of loops in Rust, each with its unique melody.


1. Loop Statement: The Infinite Symphony

The loop statement orchestrates a perpetual dance, executing a block of code until explicitly halted by the break keyword:

let counter = 1;
loop {
    println!("{counter}");
    if counter > 5 {
        break;
    }
    counter += 1;
}
// Output: 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

In this example, the loop pulses endlessly until the counter reaches 6, where the break command takes center stage.


2. While Loop: The Rhythmic Repeater

The while loop beats to the rhythm of a specified condition, executing a block of code as long as the condition holds true:

let mut counter = 1;
while counter <= 5 {
    println!("{counter}");
    counter += 1;
}
// Output: 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

As long as the counter stays less than or equal to 5, the loop's cadence persists.


3. For Loop: The Iterative Ensemble

The for loop conducts a harmonious journey through collections, be it arrays, vectors, strings, or anything implementing the Iterator trait:

Example 1: Array Serenade

let numbers = [1, 2, 3, 4, 5];
for element in numbers {
    println!("{element}");
}
// Output: 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

In this sonnet, the for loop serenades through the array of numbers, echoing each element.

Example 2: Range Sonata

for i in 1..=10 {
    println!("{i}");
}
// Output: 1 2 3 4 5 6 7 8 9 10
Enter fullscreen mode Exit fullscreen mode

The for loop orchestrates a sonata, traversing the inclusive range from 1 to 10.

Explore the symphony of functions from the Iterator trait in Rust's for loop here.

As I navigate Rust's looping landscape, each iteration unveils the language's elegance and precision. Follow my coding journey on LinkedIn for more updates! πŸ’»πŸŒβœ¨

RustLang #Programming #LearningToCode #CodeNewbie #TechJourney #Day6

Top comments (0)