我正在尝试通过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; }
}
如错误消息所提示,索引必须为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; }
}
我知道这可能实际上对您的代码@Sumchans没有帮助,但是我不得不写一个more idiomatic版本。我希望它可以帮助某人:
fn main() {
let v = vec![1,4,2,4,1,8];
v.iter().for_each(|n| println!("{}", n));
}