如何解决“不能索引`usize`类型的值的错误?

如何解决“不能索引`usize`类型的值的错误?

问题描述:

我尝试使用下面的代码来衡量Vec[]编制索引与.get(index)速度:如何解决“不能索引`usize`类型的值的错误?

extern crate time; 

fn main() { 
    let v = vec![1; 1_000_000]; 
    let before_rec1 = time::precise_time_ns(); 

    for (i, v) in (0..v.len()).enumerate() { 
     v[i] 
    } 
    let after_rec1 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec1 - before_rec1); 


    let before_rec2 = time::precise_time_ns(); 

    for (i, v) in (0..v.len()).enumerate() { 
     v.get(i) 
    } 
    let after_rec2 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec2 - before_rec2); 
} 

但这返回以下错误:

error: cannot index a value of type `usize` 
--> src/main.rs:8:9 
    | 
8 |   v[i] 
    |   ^^^^ 

error: no method named `get` found for type `usize` in the current scope 
    --> src/main.rs:17:11 
    | 
17 |   v.get(i) 
    |   ^^^ 

我很困惑,为什么这个不起作用,因为enumerate应该给我一个索引,它的名字,我应该能够用来索引向量。

  1. 为什么这个错误被抛出?
  2. 我知道我可以/应该使用迭代而不是C风格的索引方式,但为了学习,我用什么来迭代索引值,就像我在这里试图做的那样?
+3

在'的(I,V)''的是v'阴影v'的'之前的定义是你想索引的矢量。尽管您可能会优化整个循环,因为您没有在任何地方使用索引操作的结果。 – Lee

+1

请不要将**答案**添加到**问题**中。我已回滚到您的原始版本,然后应用一些正常清理。欢迎您,并鼓励,如果你认为你有什么实质性的添加到任何现有的答案来添加自己的答案。您还可以添加注释,以现有的答案,如果你只是想提供更多细节少量到现有的答案。 – Shepmaster

你,朋友,在这里是非常困惑。

fn main() { 
    let v = vec![1; 1_000_000]; 

v的类型为Vec<i32>

for (i, v) in (0..v.len()).enumerate() { 
    v[i] 
} 

你迭代的一系列指标,从0v.len(),并使用enumerate生成指数,当您去:

  • v的类型为usize
  • 在循环中,v == i ,总是

所以......确实,编译器是正确的,你不能在usize上使用[]


程序“固定”:

extern crate time; 

fn main() { 
    let v = vec![1; 1_000_000]; 

    let before_rec1 = time::precise_time_ns(); 

    for i in 0..v.len() { 
     v[i] 
    } 

    let after_rec1 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec1 - before_rec1); 


    let before_rec2 = time::precise_time_ns(); 

    for i in 0..v.len() { 
     v.get(i) 
    } 

    let after_rec2 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec2 - before_rec2); 
} 

我想补充一个免责声明,不过,如果我是一个编译器,这个没用的循环将被优化成一个空操作。如果在与--release编译后,您的程序报告0,这就是发生了什么。

锈病内置benchmarking support,我建议你使用它,而不是去用简单的方式。而且......你还需要检查发射的组件,这是确保你测量自己的想法的唯一方法(优化编译器就像那样棘手)。