diff options
| author | Camelid <camelidcamel@gmail.com> | 2021-01-07 17:29:27 -0800 |
|---|---|---|
| committer | Camelid <camelidcamel@gmail.com> | 2021-01-07 17:41:40 -0800 |
| commit | f7558991adcdf15f1cb1093810c8b05894b12dd3 (patch) | |
| tree | 8fd50b2be3b96877d0a68ff380abf38b04ec7f82 | |
| parent | c8915eebeaaef9f7cc1cff6ffd97f578b03c2ac9 (diff) | |
| download | rust-f7558991adcdf15f1cb1093810c8b05894b12dd3.tar.gz rust-f7558991adcdf15f1cb1093810c8b05894b12dd3.zip | |
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.
| -rw-r--r-- | library/core/src/iter/traits/iterator.rs | 36 |
1 files changed, 17 insertions, 19 deletions
diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 0023de65d2b..7affe0c2000 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -1535,34 +1535,32 @@ pub trait Iterator { /// /// # Examples /// - /// Basic usage: + /// This demonstrates a use case that needs `by_ref`: /// - /// ``` - /// let a = [1, 2, 3]; - /// - /// let iter = a.iter(); - /// - /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i); + /// ```compile_fail,E0382 + /// let a = [1, 2, 3, 4, 5]; + /// let mut iter = a.iter(); + /// let sum: i32 = iter.take(3).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); + /// // Error! We can't use `iter` again because it was moved + /// // by `take`. + /// assert_eq!(iter.next(), Some(&4)); + /// ``` /// - /// // let's try that again - /// let a = [1, 2, 3]; + /// Now, let's use `by_ref` to make this work: /// + /// ``` + /// let a = [1, 2, 3, 4, 5]; /// let mut iter = a.iter(); + /// // We add in a call to `by_ref` here so `iter` isn't moved. + /// let sum: i32 = iter.by_ref().take(3).fold(0, |acc, i| acc + i); /// - /// // instead, we add in a .by_ref() - /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i); - /// - /// assert_eq!(sum, 3); + /// assert_eq!(sum, 6); /// - /// // now this is just fine: - /// assert_eq!(iter.next(), Some(&3)); - /// assert_eq!(iter.next(), None); + /// // And now we can use `iter` again because we still own it. + /// assert_eq!(iter.next(), Some(&4)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn by_ref(&mut self) -> &mut Self |
