diff options
| author | Diego Ongaro <ongardie@gmail.com> | 2025-04-13 19:52:34 -0700 |
|---|---|---|
| committer | Diego Ongaro <ongardie@gmail.com> | 2025-04-13 19:52:34 -0700 |
| commit | e5fb426a833e45565f13f81c2c664e77e0e351f1 (patch) | |
| tree | 81d1f9be2e40e2721def295356122538012424e1 | |
| parent | 6e830462330a9e34d8176e86d4580dd0820c6fd5 (diff) | |
| download | rust-e5fb426a833e45565f13f81c2c664e77e0e351f1.tar.gz rust-e5fb426a833e45565f13f81c2c664e77e0e351f1.zip | |
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`.
| -rw-r--r-- | library/core/src/iter/traits/iterator.rs | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index d9534a44598..c68fd2115d6 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -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> |
