Reputation: 3784
I am trying to print the elements of a vector through the println! inside a loop.
This is the error I get, cant figure out what I am doing wrong. Please advise!
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; }
}
Upvotes: 0
Views: 491
Reputation: 81
I faced the similar problem few days ago but in a different manner when I was trying to make my bubble sort program in rust. I hope you got your answer as I can see. I think the way you wanted to print a vector is syntactically incorrect, here is an example of printing a vector in a loop. Hope this would help you.
fn main(){
let v = vec![1,3,5,7,9];
for i in v.iter(){ //also for i in &v
println!("{:?}",i);
}
}
Also you can use
let outercount = v[0]; //rust will automatically infer this as [i32]
Upvotes: 1
Reputation: 7725
I know this may not actually help your code @Sumchans, but I'm compelled to write a more idiomatic version. I hope that it helps someone:
fn main() {
let v = vec![1,4,2,4,1,8];
v.iter().for_each(|n| println!("{}", n));
}
Upvotes: 3
Reputation: 215117
As the error message suggests, index needs to be usize
instead of 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; }
}
Upvotes: 2