OneBite.Dev - Coding blog in a bite size

Do A For Loop In Rust

Code snippet for how to Do A For Loop In Rust with sample and detail explanation

In this article, we’ll be walking you through the process of creating a for loop in the Rust programming language. Though it might seem intimidating at first, like everything else in programming, with a little practice, it becomes second nature.

Code snippet: Creating a For Loop in Rust

Here’s a simple example of how to code a basic for loop in Rust:

fn main() {
    for n in 1..11 {
        println!("The value is: {}", n);
    }
}

Code Explanation for Creating a For Loop in Rust

This code snippet is a basic for loop in the Rust language which prints out the values from 1 to 10. Let’s break it down:

Firstly, fn main() { initiates the main function where your program starts running.

The next line, for n in 1..11 {, is the start of the for loop. n will be the variable that holds the current value from the range every iteration. Note the range 1..11. In Rust, two periods (..) denote a range of values, and by default, the starting value is inclusive and the ending value is exclusive. This means the loop will iterate over the range of values from 1 through 10, but not including 11.

Following that, println!("The value is: {}", n); is the body of the loop; what we want to have happen every time we iterate. In this case, we’re just printing out the value of n.

Finally, the loop ends with } which matches with the for n in 1..11 {. The main function also concludes with }, closing off the program.

This is a simple example, yet it forms the foundation of understanding and using for loops effectively in Rust. From here, you can extend the loop by adding more complex conditions, computations or even nesting loops together as per your programming needs. Practice writing this loop and see how the range, variable and body can be monkeyed with to create new results. Happy coding!

rust