无法在循环内访问向量的元素

时间:2019-12-02 00:32:18

标签: rust

我正在尝试通过println打印向量的元素!循环内。

这是我遇到的错误,无法弄清楚我在做什么错。请指教!

error[E0277]: the type `[i32]` cannot be indexed by `i32`
   |
21 |         s = v[outercount];
   |             ^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[i32]>` is not implemented for `i32`
   = note: required because of the requirements on the impl of `std::ops::Index<i32>` for `std::vec::Vec<i32>`
let v = vec![1,4,2,4,1,8];
let mut outercount:i32 = 0;
loop {
    outercount += 1;
    s = v[outercount];
    println!("{}", s);
    if outercount == (v.len() - 1) as i32 { break; }
}

3 个答案:

答案 0 :(得分:3)

我知道这实际上并不能帮助您的代码@Sumchans,但是我不得不写一个more idiomatic版本。我希望它可以帮助某人:

Fill

答案 1 :(得分:2)

如错误消息所示,索引需要为usize而不是i32

let v = vec![1,4,2,4,1,8];
let mut outercount: usize = 0;    // declare outercount as usize instead of i32
loop {
    let s = v[outercount];        // need to declare variable here
    println!("{}", s);
    outercount += 1;
    if outercount == v.len() { break; }
}

答案 2 :(得分:1)

几天前我遇到了类似的问题,但是当我试图使气泡排序程序生锈时,却以不同的方式遇到了。希望您能如我所见。我认为您要打印矢量的方式在语法上是不正确的,这是循环打印矢量的示例。希望对您有帮助。

fn main(){
let v = vec![1,3,5,7,9]; 
for i in v.iter(){ //also for i in &v 
  println!("{:?}",i);
 }
}

还可以使用

let outercount = v[0]; //rust will automatically infer this as [i32]
相关问题