]> git.lizzy.rs Git - rust.git/blobdiff - library/core/src/iter/traits/iterator.rs
Expand docs on Iterator::intersperse
[rust.git] / library / core / src / iter / traits / iterator.rs
index 91d7a47907a461b91bdd4118a3caa08b4252869e..e3b2c394e544666efee17c3ee0b62339b8b9d8e5 100644 (file)
@@ -569,7 +569,11 @@ fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
         Zip::new(self, other.into_iter())
     }
 
-    /// Places a copy of `separator` between all elements.
+    /// Creates a new iterator which places a copy of `separator` between adjacent
+    /// items of the original iterator.
+    ///
+    /// In case `separator` does not implement [`Clone`] or needs to be
+    /// computed every time, use [`intersperse_with`].
     ///
     /// # Examples
     ///
@@ -578,9 +582,25 @@ fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
     /// ```
     /// #![feature(iter_intersperse)]
     ///
-    /// let hello = ["Hello", "World"].iter().copied().intersperse(" ").collect::<String>();
-    /// assert_eq!(hello, "Hello World");
+    /// let mut a = [0, 1, 2].iter().intersperse(&100);
+    /// assert_eq!(a.next(), Some(&0));   // The first element from `a`.
+    /// assert_eq!(a.next(), Some(&100)); // The separator.
+    /// assert_eq!(a.next(), Some(&1));   // The next element from `a`.
+    /// assert_eq!(a.next(), Some(&100)); // The separator.
+    /// assert_eq!(a.next(), Some(&2));   // The last element from `a`.
+    /// assert_eq!(a.next(), None);       // The iterator is finished.
+    /// ```
+    ///
+    /// `intersperse` can be very useful to join an iterator's items using a common element:
     /// ```
+    /// #![feature(iter_intersperse)]
+    ///
+    /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
+    /// assert_eq!(hello, "Hello World !");
+    /// ```
+    ///
+    /// [`Clone`]: crate::clone::Clone
+    /// [`intersperse_with`]: Iterator::intersperse_with
     #[inline]
     #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
     fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
@@ -591,7 +611,16 @@ fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
         Intersperse::new(self, separator)
     }
 
-    /// Places an element generated by `separator` between all elements.
+    /// Creates a new iterator which places an item generated by `separator`
+    /// between adjacent items of the original iterator.
+    ///
+    /// The closure will be called exactly once each time an item is placed
+    /// between two adjacent items from the underlying iterator; specifically,
+    /// the closure is not called if the underlying iterator yields less than
+    /// two items and after the last item is yielded.
+    ///
+    /// If the iterator's item implements [`Clone`], it may be easier to use
+    /// [`intersperse`].
     ///
     /// # Examples
     ///
@@ -600,12 +629,36 @@ fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
     /// ```
     /// #![feature(iter_intersperse)]
     ///
-    /// let src = ["Hello", "to", "all", "people"].iter().copied();
-    /// let mut separator = [" ❤️ ", " 😀 "].iter().copied().cycle();
+    /// #[derive(PartialEq, Debug)]
+    /// struct NotClone(usize);
     ///
-    /// let result = src.intersperse_with(|| separator.next().unwrap()).collect::<String>();
-    /// assert_eq!(result, "Hello ❤️ to 😀 all ❤️ people");
+    /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
+    /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
+    ///
+    /// assert_eq!(it.next(), Some(NotClone(0)));  // The first element from `v`.
+    /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
+    /// assert_eq!(it.next(), Some(NotClone(1)));  // The next element from `v`.
+    /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
+    /// assert_eq!(it.next(), Some(NotClone(2)));  // The last element from from `v`.
+    /// assert_eq!(it.next(), None);               // The iterator is finished.
+    /// ```
+    ///
+    /// `intersperse_with` can be used in situations where the separator needs
+    /// to be computed:
     /// ```
+    /// #![feature(iter_intersperse)]
+    ///
+    /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
+    ///
+    /// // The closure mutably borrows it's context to generate an item.
+    /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
+    /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
+    ///
+    /// let result = src.intersperse_with(separator).collect::<String>();
+    /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
+    /// ```
+    /// [`Clone`]: crate::clone::Clone
+    /// [`intersperse`]: Iterator::intersperse
     #[inline]
     #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
     fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
@@ -830,8 +883,6 @@ fn filter<P>(self, predicate: P) -> Filter<Self, P>
     /// assert_eq!(iter.next(), Some(5));
     /// assert_eq!(iter.next(), None);
     /// ```
-    ///
-    /// [`Option<T>`]: Option
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>