As I was reading the rust documentation, I stumbled upon this code that iterates the array a
using a while loop (with an index):
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
The documentation says:
... this approach is error prone; we could cause the program to panic if the index length is incorrect. It’s also slow, because the compiler adds runtime code to perform the conditional check on every element on every iteration through the loop.
The first reason was self-explanatory. The second reason was where I got confused.
Furthermore, they suggested to use a for-loop for this.
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
I just can't seem to wrap my head around this. Is there some kind of behavior that the Rust compiler does?