Exit code 101 iterating over array with &array

Viewed 265

I was recently trying to benchmark Rust for loops using different iteration styles when I ran into this interesting error. If I iterate using the code below, I will get &[i32; 1000000] is not an iterator; maybe try calling .iter() or a similar method. I am aware that I can just use iter(), however I am trying to find which is faster, iter() or &array.

Code:

extern crate time;

fn main() {
    let array: [i32; 1000000] = [0; 1000000]; // This will produce an error
    // let array: [i32; 32] = [0; 32] produces no error

    let start_time = time::precise_time_s();
    for _x in &array {
    }
    println!("{}", time::precise_time_s() - start_time);
}

My question is: Why can't I iterate over arrays larger than 32 with &array?

1 Answers

In terms of performance, there's no difference since they use the exact same Iterator implementation. You can verify this by looking at the implementations of IntoIterator; specifically, at the IntoIter types.

The reason you can't use &array for some sizes is because Rust doesn't have generic value parameters for generics. This means there's no way for the standard library to express generics that are parameterised over some value. Like, say, array length. This means you need a distinct implementation of IntoIterator for every possible size of array. This is obviously impossible, so the standard library only implements it for a few sizes; specifically, for arrays up to 32 elements in size.

Related