Take::new(self, n)
}
- /// An iterator adapter similar to [`fold`] that holds internal state and
- /// produces a new iterator.
+ /// An iterator adapter which, like [`fold`], holds internal state, but
+ /// unlike [`fold`], produces a new iterator.
///
/// [`fold`]: Iterator::fold
///
///
/// On iteration, the closure will be applied to each element of the
/// iterator and the return value from the closure, an [`Option`], is
- /// yielded by the iterator.
+ /// returned by the `next` method. Thus the closure can return
+ /// `Some(value)` to yield `value`, or `None` to end the iteration.
///
/// # Examples
///
/// Basic usage:
///
/// ```
- /// let a = [1, 2, 3];
+ /// let a = [1, 2, 3, 4];
///
/// let mut iter = a.iter().scan(1, |state, &x| {
- /// // each iteration, we'll multiply the state by the element
+ /// // each iteration, we'll multiply the state by the element ...
/// *state = *state * x;
///
- /// // then, we'll yield the negation of the state
+ /// // ... and terminate if the state exceeds 6
+ /// if *state > 6 {
+ /// return None;
+ /// }
+ /// // ... else yield the negation of the state
/// Some(-*state)
/// });
///
/// assert_eq!(merged, "alphabetagamma");
/// ```
///
+ /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
+ ///
+ /// ```
+ /// let options = vec![Some(123), Some(321), None, Some(231)];
+ /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
+ /// assert_eq!(flattened_options, vec![123, 321, 231]);
+ ///
+ /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
+ /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
+ /// assert_eq!(flattened_results, vec![123, 321, 231]);
+ /// ```
+ ///
/// Flattening only removes one level of nesting at a time:
///
/// ```