Lesson 2
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:

Rust
1fn main() { 2 for var in range { 3 code to execute 4 } 5}
  • The for keyword starts the loop.
  • The in keyword 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:

Rust
1fn main() { 2 // For loop with range 3 for number in 1..6 { 4 println!("Number is: {}", number); 5 } 6} 7/* Output 8 Number is: 1 9 Number is: 2 10 Number is: 3 11 Number is: 4 12 Number is: 5 13*/

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.

Rust
1fn main() { 2 for number in (1..6).rev() { 3 println!("Reverse number is: {}", number); 4 } 5} 6/* Output 7 Reverse number is: 5 8 Reverse number is: 4 9 Reverse number is: 3 10 Reverse number is: 2 11 Reverse number is: 1 12*/

In this example:

  • The rev method is called on the range 1..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.

Rust
1fn main() { 2 // Using step_by to iterate 3 for number in (1..8).step_by(2) { 4 println!("{}", number); 5 } 6} 7/* Output 8 1 9 3 10 5 11 7 12*/

In this example, the loop iterates over the range 1..8 with a step size of 2.

Combining `rev` and `step_by`

You can combine rev and step_by for more complex iterations:

Rust
1fn main() { 2 // Using step_by in reverse iteration 3 println!("Iterating in reverse with a step size of 2:"); 4 for number in (1..10).rev().step_by(2) { 5 println!("{}", number); // Prints "9", "7", "5", "3", "1" 6 } 7} 8/* Output 9 9 10 7 11 5 12 3 13 1 14*/

In this example:

  • First, the range 1..10 is reversed.
  • Then, the loop steps by 2, iterating backward.
Variable Scope within For Loops

Variables declared within a for loop's body are local to that loop. This is important to keep in mind when writing more complex code:

Rust
1fn main() { 2 // for loop scope 3 for num in 1..5 { 4 let doubled = num * 2; 5 println!("{} doubled is {}", num, doubled); 6 } 7 // println!("{} doubled is {}", num, doubled); // Error because `num` and `doubled` are out of scope. 8}

In this example:

  • Each iteration of the loop has its own instance of doubled.
  • Attempting to access it outside the loop will result in a scope error.
Summary and Next Steps

Well done! You've now explored various aspects of for loops in Rust, including iterating over ranges, using rev and step_by for custom iterations, and understanding variable scope within loops.

For loops are incredibly powerful and will make your code more concise and efficient. Now it's time to apply what you've learned. Dive into the exercises ahead to solidify your understanding and see how for loops can simplify your code. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.