Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add Iterator::exhaust
  • Loading branch information
varkor committed Apr 15, 2018
commit 804532c9fd8df68e71fc491148fef512ac0d301f
26 changes: 26 additions & 0 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2251,6 +2251,32 @@ pub trait Iterator {
Product::product(self)
}

/// Eagerly consume the iterator, evaluating all the elements.
///
/// This is primarily useful for evaluating the effects of an iterator that
/// has previously been created. To evaluate the effects of an iterator
/// immediately, it is likely better to use [`for_each`].
///
/// [`for_each`]: #method.for_each
///
/// # Examples
///
/// ```
/// // Prepare an iterator with side effects...
/// let count_aloud = 1..=10.map(|x| println!("{}", x));
///
/// // ...
///
/// // Trigger the effects!
/// count_aloud.exhaust();
///
/// ```
#[inline]
#[unstable(feature = "iter_exhaust", issue = "44546")]
fn exhaust(self) where Self: Sized {
for _ in self {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should use for_each to get internal iteration, rather than (implicit) next() calls.

Copy link
Contributor Author

@varkor varkor Apr 16, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't matter so much now the PR's closed, but out of curiosity, what difference in behaviour would using for_each have?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference is that some iterators can apply a fold much more efficiently than they can next one item at a time. For instance, Chain::fold can fold its first part as a whole, then its second part as a whole, but Chain::next has to check whether it's on the first or second part every time. This is demonstrated in the benchmarks added to the for_each PR, #42782, in commit 4a8ddac.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, of course, that makes a lot of sense. Thanks for explaining!

}

/// Lexicographically compares the elements of this `Iterator` with those
/// of another.
#[stable(feature = "iter_order", since = "1.5.0")]
Expand Down