Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Iterator::by_ref example #80805

Merged
merged 4 commits into from
Apr 23, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -1538,31 +1538,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