I want to print out every value from this vector and I know I can do it with .enumerate, but I’m curious what’s wrong with this:
fn main() {
let vec = vec![1,2,3];
for i in vec.iter() {
println!("{}", vec[i as usize]);
}
}
I’m new to Rust, so go easy on me.
Here’s the error I got from the faulty code:
error[E0277]: the type `[{integer}]` cannot be indexed by `&{integer}`
--> src\main.rs:4:24
|
4 | println!("{}", vec[i]);
| ^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `SliceIndex<[{integer}]>` is not implemented for `&{integer}`
= help: the trait `SliceIndex<[T]>` is implemented for `usize`
= note: required because of the requirements on the impl of `Index<&{integer}>` for `Vec<{integer}>`
For more information about this error, try `rustc --explain E0277`.
>Solution :
i is the item being iterated and not the iterator itself.
You can use enumerate to get the iterator index variable
for (i,n) in vec.iter().enumerate()