代码之家  ›  专栏  ›  技术社区  ›  Sumchans

无法访问循环中向量的元素

  •  0
  • Sumchans  · 技术社区  · 5 年前

    我想通过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; }
    }
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   akuiper    5 年前

    如错误消息所示,索引需要 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
  •  3
  •   matiu    5 年前

    我知道这可能对你的代码@Sumchans没有帮助,但我不得不写一个 more idiomatic 版本。我希望它能帮助某些人:

    fn main() {
       let v = vec![1,4,2,4,1,8];
       v.iter().for_each(|n| println!("{}", n));
    }
    
        3
  •  1
  •   Taimoor    5 年前

    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]