Struct Peekable
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Peekable<I: Iterator> { pub(in ::iter::adapters::peekable) iter: I, pub(in ::iter::adapters::peekable) peeked: Option<Option<I::Item>> }
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.
Fields
iter: Ipeeked: Option<Option<I::Item>>Remember a peeked value, even if it was None.
Implementations
impl<I: Iterator> Peekable<I>
fn peek(&mut self) -> Option<&I::Item>Returns a reference to the next() value without advancing the iterator.
Like
next, if there is a value, it is wrapped in aSome(T). But if the iteration is over,Noneis returned.Because
peek()returns a reference, and many iterators iterate over references, there can be a possibly confusing situation where the return value is a double reference. You can see this effect in the examples below.Examples
Basic usage:
let xs = ; let mut iter = xs.iter.peekable; // peek() lets us see into the future assert_eq!; assert_eq!; assert_eq!; // The iterator does not advance even if we `peek` multiple times assert_eq!; assert_eq!; assert_eq!; // After the iterator is finished, so is `peek()` assert_eq!; assert_eq!;fn peek_mut(&mut self) -> Option<&mut I::Item>Returns a mutable reference to the next() value without advancing the iterator.
Like
next, if there is a value, it is wrapped in aSome(T). But if the iteration is over,Noneis returned.Because
peek_mut()returns a reference, and many iterators iterate over references, there can be a possibly confusing situation where the return value is a double reference. You can see this effect in the examples below.Examples
Basic usage:
let mut iter = .iter.peekable; // Like with `peek()`, we can see into the future without advancing the iterator. assert_eq!; assert_eq!; assert_eq!; // Peek into the iterator and set the value behind the mutable reference. if let Some = iter.peek_mut // The value we put in reappears as the iterator continues. assert_eq!;fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item>Consume and return the next value of this iterator if a condition is true.
If
funcreturnstruefor the next value of this iterator, consume and return it. Otherwise, returnNone.Examples
Consume a number if it's equal to 0.
let mut iter = .peekable; // The first item of the iterator is 0; consume it. assert_eq!; // The next item returned is now 1, so `next_if` will return `None`. assert_eq!; // `next_if` retains the next item if the predicate evaluates to `false` for it. assert_eq!;Consume any number less than 10.
let mut iter = .peekable; // Consume all numbers less than 10 while iter.next_if.is_some // The next value returned will be 10 assert_eq!;fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item> where T: ?Sized, I::Item: PartialEq<T>,Consume and return the next item if it is equal to
expected.Example
Consume a number if it's equal to 0.
let mut iter = .peekable; // The first item of the iterator is 0; consume it. assert_eq!; // The next item returned is now 1, so `next_if_eq` will return `None`. assert_eq!; // `next_if_eq` retains the next item if it was not equal to `expected`. assert_eq!;fn next_if_map<R>(&mut self, f: impl FnOnce(I::Item) -> Result<R, I::Item>) -> Option<R>Consumes the next value of this iterator and applies a function
fon it, returning the result if the closure returnsOk.Otherwise if the closure returns
Errthe value is put back for the next iteration.The content of the
Errvariant is typically the original value of the closure, but this is not required. If a different value is returned, the nextpeek()ornext()call will result in this new value. This is similar to modifying the output ofpeek_mut().If the closure panics, the next value will always be consumed and dropped even if the panic is caught, because the closure never returned an
Errvalue to put back.See also:
next_if_map_mut.Examples
Parse the leading decimal number from an iterator of characters.
let mut iter = "125 GOTO 10".chars.peekable; let mut line_num = 0_u32; while let Some = iter.next_if_map assert_eq!; assert_eq!;Matching custom types.
/// Combines all consecutive `Comment` nodes into a single one. # assert_eq!fn next_if_map_mut<R>(&mut self, f: impl FnOnce(&mut I::Item) -> Option<R>) -> Option<R>Gives a mutable reference to the next value of the iterator and applies a function
fto it, returning the result and advancing the iterator iffreturnsSome.Otherwise, if
freturnsNone, the next value is kept for the next iteration.If
fpanics, the item that is consumed from the iterator as ifSomewas returned fromf. The value will be dropped.This is similar to
next_if_map, except ownership of the item is not given tof. This can be preferable iffwould copy the item anyway.Examples
Parse the leading decimal number from an iterator of characters.
let mut iter = "125 GOTO 10".chars.peekable; let mut line_num = 0_u32; while let Some = iter.next_if_map_mut assert_eq!; assert_eq!;
impl<I: Iterator> Peekable<I>
const fn new(iter: I) -> Peekable<I>
Trait Implementations
impl<I> DoubleEndedIterator for Peekable<I>
where
I: DoubleEndedIterator,
fn next_back(&mut self) -> Option<Self::Item>fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc,
impl<I> SourceIter for Peekable<I>
where
I: SourceIter + Iterator,
type Source = <I as SourceIter>::Source;unsafe fn as_inner(&mut self) -> &mut I::Source
impl<I> TrustedLen for Peekable<I>
where
I: TrustedLen,
impl<I: Clone + Iterator> Clone for Peekable<I>
where
I::Item: Clone,
fn clone(&self) -> Peekable<I>
impl<I: Debug + Iterator> Debug for Peekable<I>
where
I::Item: Debug,
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I>
impl<I: FusedIterator> FusedIterator for Peekable<I>
impl<I: Iterator> Iterator for Peekable<I>
type Item = <I as Iterator>::Item;fn next(&mut self) -> Option<I::Item>fn count(self) -> usizefn nth(&mut self, n: usize) -> Option<I::Item>fn last(self) -> Option<I::Item>fn size_hint(&self) -> (usize, Option<usize>)fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc,
Auto Trait Implementations
impl<I> Freeze for Peekable<I>
where
I: Freeze,
Option<Option<<I as Iterator>::Item>>: Freeze,
impl<I> RefUnwindSafe for Peekable<I>
where
I: RefUnwindSafe,
Option<Option<<I as Iterator>::Item>>: RefUnwindSafe,
impl<I> Send for Peekable<I>
where
I: Send,
Option<Option<<I as Iterator>::Item>>: Send,
impl<I> Sync for Peekable<I>
where
I: Sync,
Option<Option<<I as Iterator>::Item>>: Sync,
impl<I> Unpin for Peekable<I>
where
I: Unpin,
Option<Option<<I as Iterator>::Item>>: Unpin,
impl<I> UnsafeUnpin for Peekable<I>
where
I: UnsafeUnpin,
Option<Option<<I as Iterator>::Item>>: UnsafeUnpin,
impl<I> UnwindSafe for Peekable<I>
where
I: UnwindSafe,
Option<Option<<I as Iterator>::Item>>: UnwindSafe,
Blanket Implementations
impl<I> IntoIterator for Peekable<I>
where
I: Iterator,
type Item = <I as Iterator>::Item;type IntoIter = I;fn into_iter(self) -> I
impl<T> Any for Peekable<I>
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for Peekable<I>
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for Peekable<I>
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> CloneToUninit for Peekable<I>
where
T: Clone,
unsafe fn clone_to_uninit(&self, dest: *mut u8)
impl<T> From<T> for Peekable<I>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> SizeHint for Peekable<I>
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for Peekable<I>
impl<T, U> Into<U> for Peekable<I>
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for Peekable<I>
where
U: Into<T>,
type Error = Infallible;fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for Peekable<I>
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>