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:
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.