Skip to content

Commit 1dd207c

Browse files
committed
doc: clearer and more correct Iterator::scan
The `Iterator::scan` documentation seemed a little misleading to my newcomer eyes, and this tries to address that. * I found “similar to `fold`” unhelpful because (a) the similarity is only that they maintain state between iterations, and (b) the _dissimilarity_ is no less important: one returns a final value and the other an iterator. So this replaces that with “which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. * I found “the return value from the closure, an [`Option`], is yielded by the iterator” to be downright incorrect, because “yielded by the iterator” means “returned by the `next` method wrapped in `Some`”, so this implied that `scan` would convert an input iterator of `T` to an output iterator of `Option<T>`. So this replaces “yielded by the iterator” with “returned by the `next` method” and elaborates: “Thus the closure can return `Some(value)` to yield `value`, or `None` to end the iteration.” * This also changes the example to illustrate the latter point by returning `None` to terminate the iteration early based on `state`.
1 parent f1a8854 commit 1dd207c

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1380,8 +1380,8 @@ pub trait Iterator {
13801380
Take::new(self, n)
13811381
}
13821382

1383-
/// An iterator adapter similar to [`fold`] that holds internal state and
1384-
/// produces a new iterator.
1383+
/// An iterator adapter which, like [`fold`], holds internal state, but
1384+
/// unlike [`fold`], produces a new iterator.
13851385
///
13861386
/// [`fold`]: Iterator::fold
13871387
///
@@ -1393,20 +1393,25 @@ pub trait Iterator {
13931393
///
13941394
/// On iteration, the closure will be applied to each element of the
13951395
/// iterator and the return value from the closure, an [`Option`], is
1396-
/// yielded by the iterator.
1396+
/// returned by the `next` method. Thus the closure can return
1397+
/// `Some(value)` to yield `value`, or `None` to end the iteration.
13971398
///
13981399
/// # Examples
13991400
///
14001401
/// Basic usage:
14011402
///
14021403
/// ```
1403-
/// let a = [1, 2, 3];
1404+
/// let a = [1, 2, 3, 4];
14041405
///
14051406
/// let mut iter = a.iter().scan(1, |state, &x| {
1406-
/// // each iteration, we'll multiply the state by the element
1407+
/// // each iteration, we'll multiply the state by the element ...
14071408
/// *state = *state * x;
14081409
///
1409-
/// // then, we'll yield the negation of the state
1410+
/// // ... and terminate if the state exceeds 6
1411+
/// if (*state > 6) {
1412+
/// return None;
1413+
/// }
1414+
/// // ... else yield the negation of the state
14101415
/// Some(-*state)
14111416
/// });
14121417
///

0 commit comments

Comments
 (0)