Struct core::iter::Peekable
[−]
[src]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct Peekable<I: Iterator> { // some fields omitted }1.0.0
An iterator with a peek()
that returns an optional reference to the next
element.
This struct
is created by the peekable()
method on Iterator
. See its
documentation for more.
Methods
impl<I: Iterator> Peekable<I>
fn peek(&mut self) -> Option<&I::Item>
Returns a reference to the next() value without advancing the iterator.
The peek()
method will return the value that a call to next()
would
return, but does not advance the iterator. Like next()
, if there is
a value, it's wrapped in a Some(T)
, but if the iterator is over, it
will return None
.
Because peek()
returns reference, and many iterators iterate over
references, this leads to a possibly confusing situation where the
return value is a double reference. You can see this effect in the
examples below, with &&i32
.
Examples
Basic usage:
fn main() { let xs = [1, 2, 3]; let mut iter = xs.iter().peekable(); // peek() lets us see into the future assert_eq!(iter.peek(), Some(&&1)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), Some(&2)); // we can peek() multiple times, the iterator won't advance assert_eq!(iter.peek(), Some(&&3)); assert_eq!(iter.peek(), Some(&&3)); assert_eq!(iter.next(), Some(&3)); // after the iterator is finished, so is peek() assert_eq!(iter.peek(), None); assert_eq!(iter.next(), None); }let xs = [1, 2, 3]; let mut iter = xs.iter().peekable(); // peek() lets us see into the future assert_eq!(iter.peek(), Some(&&1)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), Some(&2)); // we can peek() multiple times, the iterator won't advance assert_eq!(iter.peek(), Some(&&3)); assert_eq!(iter.peek(), Some(&&3)); assert_eq!(iter.next(), Some(&3)); // after the iterator is finished, so is peek() assert_eq!(iter.peek(), None); assert_eq!(iter.next(), None);
fn is_empty(&mut self) -> bool
peekable_is_empty
#32111)Checks if the iterator has finished iterating.
Returns true
if there are no more elements in the iterator, and
false
if there are.
Examples
Basic usage:
#![feature(peekable_is_empty)] fn main() { let xs = [1, 2, 3]; let mut iter = xs.iter().peekable(); // there are still elements to iterate over assert_eq!(iter.is_empty(), false); // let's consume the iterator iter.next(); iter.next(); iter.next(); assert_eq!(iter.is_empty(), true); }#![feature(peekable_is_empty)] let xs = [1, 2, 3]; let mut iter = xs.iter().peekable(); // there are still elements to iterate over assert_eq!(iter.is_empty(), false); // let's consume the iterator iter.next(); iter.next(); iter.next(); assert_eq!(iter.is_empty(), true);