Skip to content

Commit f755899

Browse files
committed
Improve Iterator::by_ref example
I split the example into two: one that fails to compile, and one that works. I also made them identical except for the addition of `by_ref` so we don't confuse readers with random differences.
1 parent c8915ee commit f755899

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

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

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,34 +1535,32 @@ pub trait Iterator {
15351535
///
15361536
/// # Examples
15371537
///
1538-
/// Basic usage:
1538+
/// This demonstrates a use case that needs `by_ref`:
15391539
///
1540-
/// ```
1541-
/// let a = [1, 2, 3];
1542-
///
1543-
/// let iter = a.iter();
1544-
///
1545-
/// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1540+
/// ```compile_fail,E0382
1541+
/// let a = [1, 2, 3, 4, 5];
1542+
/// let mut iter = a.iter();
1543+
/// let sum: i32 = iter.take(3).fold(0, |acc, i| acc + i);
15461544
///
15471545
/// assert_eq!(sum, 6);
15481546
///
1549-
/// // if we try to use iter again, it won't work. The following line
1550-
/// // gives "error: use of moved value: `iter`
1551-
/// // assert_eq!(iter.next(), None);
1547+
/// // Error! We can't use `iter` again because it was moved
1548+
/// // by `take`.
1549+
/// assert_eq!(iter.next(), Some(&4));
1550+
/// ```
15521551
///
1553-
/// // let's try that again
1554-
/// let a = [1, 2, 3];
1552+
/// Now, let's use `by_ref` to make this work:
15551553
///
1554+
/// ```
1555+
/// let a = [1, 2, 3, 4, 5];
15561556
/// let mut iter = a.iter();
1557+
/// // We add in a call to `by_ref` here so `iter` isn't moved.
1558+
/// let sum: i32 = iter.by_ref().take(3).fold(0, |acc, i| acc + i);
15571559
///
1558-
/// // instead, we add in a .by_ref()
1559-
/// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1560-
///
1561-
/// assert_eq!(sum, 3);
1560+
/// assert_eq!(sum, 6);
15621561
///
1563-
/// // now this is just fine:
1564-
/// assert_eq!(iter.next(), Some(&3));
1565-
/// assert_eq!(iter.next(), None);
1562+
/// // And now we can use `iter` again because we still own it.
1563+
/// assert_eq!(iter.next(), Some(&4));
15661564
/// ```
15671565
#[stable(feature = "rust1", since = "1.0.0")]
15681566
fn by_ref(&mut self) -> &mut Self

0 commit comments

Comments
 (0)