rust iterate over array
To iterate over the elements of an array in Rust, you can use a for
loop:
rust iterate over array
let a = [1, 2, 3, 4, 5]; for element in a.iter() { println!("{}", element); }
This will print the elements of the array a
on separate lines.
You can also use a for
loop with an enumerated iterator to get the index and value of each element:
for (i, element) in a.iter().enumerate() { println!("The value at index {} is {}", i, element); }
You can also use a while
loop to iterate over the elements of an array, like this:
let mut i = 0; while i < a.len() { println!("{}", a[i]); i += 1; }