Lost on collecting iterators usize?


I am trying to iterate over pixels, using the image crate.

I thought, if something returns an iterator, you can call collect to take the collection, and store it in a Vector. But, I am getting stuck with this error, about usize.


fn main() -> Result<(), Box<dyn Error>> {
    let gray_img = open("model-y.jpeg")?.to_luma();
    let image_pixels: Vec<_> = gray_img.pixels().collect();

    for i in image_pixels {
        println!("Pixel: {:?}", image_pixels[i]);



error[E0277]: the type `[&image::color::Luma<u8>]` cannot be indexed by `&image::color::Luma<u8>`
  --> src/main.rs:42:33
42 |         println!("Pixel: {:?}", image_pixels[i]);
   |                                 ^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   = help: the trait `std::slice::SliceIndex<[&image::color::Luma<u8>]>` is not implemented for `&image::color::Luma<u8>`
   = note: required because of the requirements on the impl of `std::ops::Index<&image::color::Luma<u8>>` for `std::vec::Vec<&image::color::Luma<u8>>`

I am not sure how to interpret the error, or how to proceed. Any help would be very appreciated.

In for i in image_pixels the i refers to an element of image_pixels, not an index. This means that you can directly print i.

1 Like

Oh duh, thanks for the quick response!

Then, my next question is, how would I access the index, like I was trying to do? I saw that I could use .enumerate() and use this:

    for (i, pixel) in image_pixels {
        println!("Pixel: {:?}", image_pixels[i]);

but I still can't access image_pixels via an index.

Use the enumerate() iterator adapter to access the index in addition to the item. You do not need to index image_pixels in a for loop. The iterator produces item directly.

for (i, pixel) in image_pixels.iter().enumerate() {
    println!("Pixel {}: {:?}", i, pixel);


If you need to access four items at a time, you can do that with chunks_exact(4):

for pixel in image_pixels.chunks_exact(4) {
    println!("Pixel: {:?}", pixel);


Thank you. In the case I am working on, I do need the index, and now I know I shouldn't use a for loop.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.