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:
-
fn main() { ... }
: Themain
function is the entry point of our Rust program. -
let arr = [10, 20, 30, 40, 50];
: We define an arrayarr
with five integers. -
for i in &arr { ... }
: Here’s where the iteration takes place. Thefor
loop in Rust works much like it does in other languages. It iterates over elements in a collection, in this case,arr
. The&
beforearr
is a reference to the array, which allows the loop to iterate over each element without taking the ownership ofarr
. -
println!("{}", i)
: Through each iteration, this line prints the current element of the array. The{}
in theprintln!
statement is a placeholder that gets filled with the value ofi
.
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.