OneBite.Dev - Coding blog in a bite size

Iterate Over An Array In Rust

Code snippet for how to Iterate Over An Array In Rust with sample and detail explanation

Rust programming language offers a plethora of ways to perform various tasks including iterating over an array. This article discusses a simple and straightforward method to iterate over an array in Rust programming language.

Code Snippet for Array Iteration

Here’s a short code snippet to iterate over an array in Rust:

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

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

Code Explanation for Array Iteration

Let’s break down the above code to understand how it works:

  1. fn main() { ... }: The main function is the entry point of our Rust program.

  2. let arr = [10, 20, 30, 40, 50];: We define an array arr with five integers.

  3. for i in &arr { ... }: Here’s where the iteration takes place. The for loop in Rust works much like it does in other languages. It iterates over elements in a collection, in this case, arr. The & before arr is a reference to the array, which allows the loop to iterate over each element without taking the ownership of arr.

  4. println!("{}", i): Through each iteration, this line prints the current element of the array. The {} in the println! statement is a placeholder that gets filled with the value of i.

This concludes the basic explanation of how to iterate over an array in Rust. Keep in mind, Rust is a flexible language offering many ways to achieve the same operation. The above-mentioned method is simple and ideal for beginners. For more complex arrays or different requirements, there might be more efficient solutions using Rust’s powerful features and extensive standard library.

rust