Ste*_*ery 4 arrays loops for-loop rust
当我遇到这个有趣的错误时,我最近尝试使用不同的迭代样式对Rust for循环进行基准测试.如果我使用下面的代码迭代,我会得到&[i32; 1000000] is not an iterator; maybe try calling .iter() or a similar method.我知道我可以使用iter(),但是我试图找到哪个更快,iter()或者&array.
码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么我不能迭代大于32的数组&array?
在性能方面,没有区别,因为它们使用完全相同的Iterator实现.您可以通过查看实现IntoIterator来验证这一点; 特别是在IntoIter类型上.
你不能使用&array某些大小的原因是因为Rust没有泛型的通用值参数.这意味着标准库无法表达通过某些值进行参数化的泛型.比方说,数组长度.这意味着您需要IntoIterator针对每个可能的数组大小执行不同的实现.这显然是不可能的,因此标准库仅针对几种尺寸实现它; 特别是对于最多32个元素的数组.