mirror of
https://github.com/rust-lang/rust.git
synced 2025-05-14 02:49:40 +00:00
Rollup merge of #99244 - gthb:doc-improve-iterator-scan, r=m-ou-se
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`.
This commit is contained in:
commit
80e309f798
@ -1381,8 +1381,8 @@ pub trait Iterator {
|
||||
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
|
||||
///
|
||||
@ -1394,20 +1394,25 @@ pub trait Iterator {
|
||||
///
|
||||
/// 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)
|
||||
/// });
|
||||
///
|
||||
|
Loading…
Reference in New Issue
Block a user