Skip to content

Commit 4ebdb28

Browse files
authored
Rollup merge of rust-lang#139780 - ongardie:iterator-take-by_ref-example, r=workingjubilee
docs: Add example to `Iterator::take` with `by_ref` If you want to logically split an iterator after `n` items, you might first discover `take`. Before this change, you'd find that `take` consumes the iterator, and you'd probably be stuck. The answer involves `by_ref`, but that's hard to discover, especially since `by_ref` is a bit abstract and `Iterator` has many methods. After this change, you'd see the example showing `take` along with `by_ref`, which allows you to continue using the rest of the iterator. `by_ref` had a good example involving `take` already, so this change just duplicates that existing example under `take`.
2 parents d4b2210 + e5fb426 commit 4ebdb28

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

library/core/src/iter/traits/iterator.rs

+18
Original file line numberDiff line numberDiff line change
@@ -1340,6 +1340,24 @@ pub trait Iterator {
13401340
/// assert_eq!(iter.next(), Some(2));
13411341
/// assert_eq!(iter.next(), None);
13421342
/// ```
1343+
///
1344+
/// Use [`by_ref`] to take from the iterator without consuming it, and then
1345+
/// continue using the original iterator:
1346+
///
1347+
/// ```
1348+
/// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1349+
///
1350+
/// // Take the first two words.
1351+
/// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1352+
/// assert_eq!(hello_world, vec!["hello", "world"]);
1353+
///
1354+
/// // Collect the rest of the words.
1355+
/// // We can only do this because we used `by_ref` earlier.
1356+
/// let of_rust: Vec<_> = words.collect();
1357+
/// assert_eq!(of_rust, vec!["of", "Rust"]);
1358+
/// ```
1359+
///
1360+
/// [`by_ref`]: Iterator::by_ref
13431361
#[inline]
13441362
#[stable(feature = "rust1", since = "1.0.0")]
13451363
fn take(self, n: usize) -> Take<Self>

0 commit comments

Comments
 (0)