Skip to content

docs: Add example to Iterator::take with by_ref #139780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2025
Merged
Changes from all commits
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
18 changes: 18 additions & 0 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1340,6 +1340,24 @@ pub trait Iterator {
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Use [`by_ref`] to take from the iterator without consuming it, and then
/// continue using the original iterator:
///
/// ```
/// let mut words = ["hello", "world", "of", "Rust"].into_iter();
///
/// // Take the first two words.
/// let hello_world: Vec<_> = words.by_ref().take(2).collect();
/// assert_eq!(hello_world, vec!["hello", "world"]);
///
/// // Collect the rest of the words.
/// // We can only do this because we used `by_ref` earlier.
/// let of_rust: Vec<_> = words.collect();
/// assert_eq!(of_rust, vec!["of", "Rust"]);
/// ```
///
/// [`by_ref`]: Iterator::by_ref
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take(self, n: usize) -> Take<Self>
Expand Down
Loading