退出代码101使用&array迭代数组

问题描述 投票:4回答:1

当我遇到这个有趣的错误时,我最近尝试使用不同的迭代样式对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);
}

我的问题是:为什么我不能用&array迭代大于32的数组?

arrays loops for-loop rust
1个回答
6
投票

在性能方面,没有区别,因为他们使用完全相同的Iterator实现。您可以通过查看implementations of IntoIterator来验证这一点;特别是在IntoIter类型。

你不能在某些尺寸上使用&array的原因是因为Rust没有泛型的通用值参数。这意味着标准库无法表达通过某些值进行参数化的泛型。比方说,数组长度。这意味着您需要为每个可能的数组大小实现IntoIterator的独特实现。这显然是不可能的,因此标准库仅针对几种尺寸实现它;特别是对于最多32个元素的数组。

© www.soinside.com 2019 - 2024. All rights reserved.