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

How to get the current item from iterator

Is it possible to get the current item from an iterator in Rust?

I would like the same functionality as .next() but it wouldn’t continue to the next item, it would just return the current item.

so:

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

fn main() {
    let x = vec![1, 2, 3, 4, 5];

    let iterator = x.iter(); // Create an iterator

    // y is now just a single i32 from the x array
    let y = iterator.next().unwrap();

    // I'm looking for method that will return the current item from the iterator
    // Something like iterator.current() which is not implemented for some reason.
    let z = iterator.current();
}

>Solution :

You can wrap your iterator in Peekable:

fn main() {
    let x = vec![1, 2, 3, 4, 5];

    let iterator = x.iter().peekable();

    let y = iterator.next().unwrap();

    let z = iterator.peek();
}

peek() returns the about-to-be-yielded item, i.e. the item that will be returned next time you’ll call next(). Note that it returns a reference and not an owned item.

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