Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I convert i to usize in iterator function?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading