Skip to content

Commit

Permalink
Improve example of Iterator::reduce
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Sep 28, 2022
1 parent a925e20 commit 49b25d3
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2431,22 +2431,13 @@ pub trait Iterator {
///
/// # Example
///
/// Find the maximum value:
///
/// ```
/// fn find_max<I>(iter: I) -> Option<I::Item>
/// where I: Iterator,
/// I::Item: Ord,
/// {
/// iter.reduce(|accum, item| {
/// if accum >= item { accum } else { item }
/// })
/// }
/// let a = [10, 20, 5, -23, 0];
/// let b: [u32; 0] = [];
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
/// assert_eq!(reduced, 45);
///
/// assert_eq!(find_max(a.iter()), Some(&20));
/// assert_eq!(find_max(b.iter()), None);
/// // Which is equivalent to doing it with `fold`:
/// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
/// assert_eq!(reduced, folded);
/// ```
#[inline]
#[stable(feature = "iterator_fold_self", since = "1.51.0")]
Expand Down

0 comments on commit 49b25d3

Please sign in to comment.