OneBite.Dev - Coding blog in a bite size

Loop Array In Rust

Code snippet for how to Loop Array In Rust with sample and detail explanation

Rust is an innovative systems programming language that offers excellent concurrency and high memory safety. This article is set to discuss how you can loop array in Rust via easy-to-understand code snippets and step-by-step explanations.

Code snippet for Looping Array in Rust

Here is a simple Rust code snippet for looping over an array:

fn main() {
    let arr = [10, 20, 30, 40, 50];

    for i in &arr {
        println!("{}", i);
    }
}

Code Explanation for Looping Array in Rust

This code functions as a simple yet clear example of array looping in Rust. Let’s get a closer look at the code block above to understand how this process works.

  1. fn main() { }: This is the main function where our code lives. Every Rust program has a main function.

  2. let arr = [10, 20, 30, 40, 50];: Here, we are declaring and initializing an integer array ‘arr’ with five elements. ‘let’ is a keyword used in Rust for variable declaration.

  3. for i in &arr { }: This is the for loop that traverses the array. The ‘for’ keyword denotes a for loop in Rust, ‘in’ is used to retrieve elements from the array, and ‘&arr’ signifies a reference to the array.

  4. println!("{}", i);: Inside the loop, each element of the array is printed. ‘println!’ is a macro in Rust that prints to the standard output. {} are placeholders that get replaced with the values we want to print, and ‘i’ herein is the current element of the array for each iteration.

Each pass through the loop, ‘i’ takes on the value of the next element in the array until all elements are exhausted. The loop then automatically terminates. It’s important to note that Rust arrays are zero-indexed, meaning they start counting at 0. Thus, the above array ‘arr’ has indices ranging from 0 (for the first element 10) to 4 (for the last element 50).

rust