3 ms·
pcwalton or someone else who understands the issue more deeply here, but my current understanding is this: Imagine we want to print out every single element of
by steveklabnik 12y ago
pcwalton or someone else who understands the issue more deeply here, but my current understanding is this:
Imagine we want to print out every single element of a `Vec`, Rust's growable array type. Here's the code with a loop:
fn main() {
let v = vec!(1, 2, 3);
for i in range(0, v.len()) {
println!("Number {}", v.get(i));
}
}
This of course, has to check that it's only iterated the maximum number of times. The check I'm referring to, though, is in `v.get`. That has to do a bounds check on the array. If we use the iterator version...
fn main() {
let v = vec!(1, 2, 3);
for i in v.iter() {
println!("Number {}", i);
}
}
Now we get each element out of the vector. No more bounds check!