Skip to content

Commit

Permalink
Rollup merge of #80805 - camelid:iter-by_ref-example, r=steveklabnik
Browse files Browse the repository at this point in the history
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
  • Loading branch information
JohnTitor committed Apr 23, 2021
2 parents 484c619 + 49ccc3f commit dcb4083
Showing 1 changed file with 8 additions and 23 deletions.
31 changes: 8 additions & 23 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1646,31 +1646,16 @@ pub trait Iterator {
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let iter = a.iter();
///
/// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
///
/// assert_eq!(sum, 6);
///
/// // if we try to use iter again, it won't work. The following line
/// // gives "error: use of moved value: `iter`
/// // assert_eq!(iter.next(), None);
/// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
///
/// // let's try that again
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// // instead, we add in a .by_ref()
/// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
/// // Take the first two words.
/// let hello_world: Vec<_> = words.by_ref().take(2).collect();
/// assert_eq!(hello_world, vec!["hello", "world"]);
///
/// assert_eq!(sum, 3);
///
/// // now this is just fine:
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), None);
/// // Collect the rest of the words.
/// // We can only do this because we used `by_ref` earlier.
/// let of_rust: Vec<_> = words.collect();
/// assert_eq!(of_rust, vec!["of", "Rust"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn by_ref(&mut self) -> &mut Self
Expand Down

0 comments on commit dcb4083

Please sign in to comment.