For Loops in Rust
Introduction to For Loops in Rust
Hello! In this lesson, we're going to dive into for loops in Rust — a fundamental control structure used to iterate over sequences. For loops allow you to iterate over a range of numbers, items in a collection, or even characters in a string. Mastering for loops is critical for writing efficient and readable code. Let's dive in!
Basic For Loop Syntax
A for loop in Rust iterates over a range or a collection. The basic syntax looks like this:
- The
forkeyword starts the loop. - The
inkeyword specifies the range or collection to iterate over. - The code block inside
{}runs for each item in the specified range.
Let's take a look at an example:
The syntax 1..6 is a range expression in Rust that represents a sequence of numbers starting from 1 up to, but not including, 6. It uses the .. operator to create this range. So, 1..6 generates the sequence: 1, 2, 3, 4, 5.
In each iteration of the loop, the variable number takes on the specified value in the range.
Iterating in Reverse
Rust provides a convenient way to iterate in reverse using the rev method. The range includes the integers 1 up to, but not including, 6. Since the last element of the range is 5, the for loop starts at 5 and continues down to 1.
In this example:
- The
revmethod is called on the range1..6. - This makes the loop iterate from 5 down to 1.
Using `step_by` for Custom Increments
Sometimes, you may need to iterate with a custom step size. The step_by method allows you to specify the step size. step_by takes an integer argument that specifies the number of steps to jump.
In this example, the loop iterates over the range 1..8 with a step size of 2.
