Skip to content

Commit dcb4083

Browse files
authored
Rollup merge of #80805 - camelid:iter-by_ref-example, r=steveklabnik
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. cc `@steveklabnik,` who is the one that added the previous version of this example
2 parents 484c619 + 49ccc3f commit dcb4083

File tree

1 file changed

+8
-23
lines changed

1 file changed

+8
-23
lines changed

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

+8-23
Original file line numberDiff line numberDiff line change
@@ -1646,31 +1646,16 @@ pub trait Iterator {
16461646
/// Basic usage:
16471647
///
16481648
/// ```
1649-
/// let a = [1, 2, 3];
1650-
///
1651-
/// let iter = a.iter();
1652-
///
1653-
/// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1654-
///
1655-
/// assert_eq!(sum, 6);
1656-
///
1657-
/// // if we try to use iter again, it won't work. The following line
1658-
/// // gives "error: use of moved value: `iter`
1659-
/// // assert_eq!(iter.next(), None);
1649+
/// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
16601650
///
1661-
/// // let's try that again
1662-
/// let a = [1, 2, 3];
1663-
///
1664-
/// let mut iter = a.iter();
1665-
///
1666-
/// // instead, we add in a .by_ref()
1667-
/// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1651+
/// // Take the first two words.
1652+
/// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1653+
/// assert_eq!(hello_world, vec!["hello", "world"]);
16681654
///
1669-
/// assert_eq!(sum, 3);
1670-
///
1671-
/// // now this is just fine:
1672-
/// assert_eq!(iter.next(), Some(&3));
1673-
/// assert_eq!(iter.next(), None);
1655+
/// // Collect the rest of the words.
1656+
/// // We can only do this because we used `by_ref` earlier.
1657+
/// let of_rust: Vec<_> = words.collect();
1658+
/// assert_eq!(of_rust, vec!["of", "Rust"]);
16741659
/// ```
16751660
#[stable(feature = "rust1", since = "1.0.0")]
16761661
fn by_ref(&mut self) -> &mut Self

0 commit comments

Comments
 (0)