OneBite.Dev - Coding blog in a bite size

Use A Basic Loop In Rust

Code snippet for how to Use A Basic Loop In Rust with sample and detail explanation

Rust, a popular systems programming language, offers various mechanisms for repetitive tasks, including loops. This article will demonstrate a simple example of using a basic loop in Rust.

Code Snippet: Use a Basic Loop in Rust

Let’s start with a simple snippet of a basic loop in Rust:

fn main() {
    for i in 1..11 {
        println!("Number: {}", i);
    }
}

Code Explanation: Use a Basic Loop in Rust

The given Rust code snippet demonstrates a simple loop - more specifically, a for loop.

Let’s break down the code step by step:

  1. Function Declaration: The first line fn main() { starts the declaration of the main function. This is the starting point for all Rust programs.

  2. Loop Initialization: The second line for i in 1..11 { starts the for loop. The .. operator creates a range of values. In this case, it creates a sequence of numbers from 1 to 10 (Rust ranges are exclusive of the ending number). The i is the control variable that takes each value in the range, one by one.

  3. Under Loop Operation: The third line println!("Number: {}", i); is the operation to be performed in each iteration of the loop. The println! macro prints out the number of the current iteration. The {} inside the string is a placeholder that gets replaced by the value of i.

  4. Ending the Loop and the Function: The last two lines } simply mark the end of the for loop and the main function respectively.

Try to run this Rust program, and it will print the numbers from 1 to 10, showing how you can achieve basic iteration in Rust using a for loop.

rust