diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 5353fcaa3b4..262bfd5de99 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -312,46 +312,110 @@ use usize; fn _assert_is_object_safe(_: &Iterator) {} -/// An interface for dealing with "external iterators". These types of iterators -/// can be resumed at any time as all state is stored internally as opposed to -/// being located on the call stack. +/// An interface for dealing with iterators. /// -/// The Iterator protocol states that an iterator yields a (potentially-empty, -/// potentially-infinite) sequence of values, and returns `None` to signal that -/// it's finished. The Iterator protocol does not define behavior after `None` -/// is returned. A concrete Iterator implementation may choose to behave however -/// it wishes, either by returning `None` infinitely, or by doing something -/// else. +/// This is the main iterator trait. For more about the concept of iterators +/// generally, please see the [module-level documentation]. In particular, you +/// may want to know how to [implement `Iterator`][impl]. +/// +/// [module-level documentation]: index.html +/// [impl]: index.html#implementing-iterator #[lang = "iterator"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \ `.iter()` or a similar method"] pub trait Iterator { - /// The type of the elements being iterated + /// The type of the elements being iterated over. #[stable(feature = "rust1", since = "1.0.0")] type Item; - /// Advances the iterator and returns the next value. Returns `None` when the - /// end is reached. - #[stable(feature = "rust1", since = "1.0.0")] - fn next(&mut self) -> Option; - - /// Returns a lower and upper bound on the remaining length of the iterator. + /// Advances the iterator and returns the next value. /// - /// An upper bound of `None` means either there is no known upper bound, or - /// the upper bound does not fit within a `usize`. + /// Returns `None` when iteration is finished. Individual iterator + /// implementations may choose to resume iteration, and so calling `next()` + /// again may or may not eventually start returning `Some(Item)` again at some + /// point. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let it = (0..10).filter(|x| x % 2 == 0).chain(15..20); - /// assert_eq!((5, Some(15)), it.size_hint()); + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// // A call to next() returns the next value... + /// assert_eq!(Some(&1), iter.next()); + /// assert_eq!(Some(&2), iter.next()); + /// assert_eq!(Some(&3), iter.next()); + /// + /// // ... and then None once it's over. + /// assert_eq!(None, iter.next()); + /// + /// // More calls may or may not return None. Here, they always will. + /// assert_eq!(None, iter.next()); + /// assert_eq!(None, iter.next()); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + fn next(&mut self) -> Option; + + /// Returns the bounds on the remaining length of the iterator. + /// + /// Specifically, `size_hint()` returns a tuple where the first element + /// is the lower bound, and the second element is the upper bound. + /// + /// The second half of the tuple that is returned is an `Option`. A + /// `None` here means that either there is no known upper bound, or the + /// upper bound is larger than `usize`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// let a = [1, 2, 3]; + /// let iter = a.iter(); + /// + /// assert_eq!((3, Some(3)), iter.size_hint()); + /// ``` + /// + /// A more complex example: + /// + /// ``` + /// // The even numbers from zero to ten. + /// let iter = (0..10).filter(|x| x % 2 == 0); + /// + /// // We might iterate from zero to ten times. Knowing that it's five + /// // exactly wouldn't be possible without executing filter(). + /// assert_eq!((0, Some(10)), iter.size_hint()); + /// + /// // Let's add one five more numbers with chain() + /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20); + /// + /// // now both bounds are increased by five + /// assert_eq!((5, Some(15)), iter.size_hint()); + /// ``` + /// + /// Returning `None` for an upper bound: + /// + /// ``` + /// // an infinite iterator has no upper bound + /// let iter = (0..); + /// + /// assert_eq!((0, None), iter.size_hint()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn size_hint(&self) -> (usize, Option) { (0, None) } - /// Counts the number of elements in this iterator. + /// Consumes the iterator, counting the number of iterations and returning it. + /// + /// This method will evaluate the iterator until its [`next()`] returns + /// `None`. Once `None` is encountered, `count()` returns the number of + /// times it called [`next()`]. + /// + /// [`next()`]: #method.next /// /// # Overflow Behavior /// @@ -362,12 +426,17 @@ pub trait Iterator { /// /// # Panics /// - /// This functions might panic if the iterator has more than `usize::MAX` + /// This function might panic if the iterator has more than `usize::MAX` /// elements. /// /// # Examples /// + /// Basic usage: + /// /// ``` + /// let a = [1, 2, 3]; + /// assert_eq!(a.iter().count(), 3); + /// /// let a = [1, 2, 3, 4, 5]; /// assert_eq!(a.iter().count(), 5); /// ``` @@ -378,11 +447,20 @@ pub trait Iterator { self.fold(0, |cnt, _| cnt + 1) } - /// Loops through the entire iterator, returning the last element. + /// Consumes the iterator, returning the last element. + /// + /// This method will evaluate the iterator until it returns `None`. While + /// doing so, it keeps track of the current element. After `None` is + /// returned, `last()` will then return the last element it saw. /// /// # Examples /// + /// Basic usage: + /// /// ``` + /// let a = [1, 2, 3]; + /// assert_eq!(a.iter().last(), Some(&3)); + /// /// let a = [1, 2, 3, 4, 5]; /// assert_eq!(a.iter().last(), Some(&5)); /// ``` @@ -394,15 +472,45 @@ pub trait Iterator { last } - /// Skips the `n` first elements of the iterator and returns the next one. + /// Consumes the `n` first elements of the iterator, then returns the + /// `next()` one. + /// + /// This method will evaluate the iterator `n` times, discarding those elements. + /// After it does so, it will call [`next()`] and return its value. + /// + /// [`next()`]: #method.next + /// + /// Like most indexing operations, the count starts from zero, so `nth(0)` + /// returns the first value, `nth(1)` the second, and so on. + /// + /// `nth()` will return `None` if `n` is larger than the length of the + /// iterator. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter(); - /// assert_eq!(it.nth(2), Some(&3)); - /// assert_eq!(it.nth(2), None); + /// let a = [1, 2, 3]; + /// assert_eq!(a.iter().nth(1), Some(&2)); + /// ``` + /// + /// Calling `nth()` multiple times doesn't rewind the iterator: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert_eq!(iter.nth(1), Some(&2)); + /// assert_eq!(iter.nth(1), None); + /// ``` + /// + /// Returning `None` if there are less than `n` elements: + /// + /// ``` + /// let a = [1, 2, 3]; + /// assert_eq!(a.iter().nth(10), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -414,19 +522,54 @@ pub trait Iterator { None } - /// Chain this iterator with another, returning a new iterator that will - /// finish iterating over the current iterator, and then iterate - /// over the other specified iterator. + /// Takes two iterators and creates a new iterator over both in sequence. + /// + /// `chain()` will return a new iterator which will first iterate over + /// values from the first iterator and then over values from the second + /// iterator. + /// + /// In other words, it links two iterators together, in a chain. 🔗 /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [0]; - /// let b = [1]; - /// let mut it = a.iter().chain(&b); - /// assert_eq!(it.next(), Some(&0)); - /// assert_eq!(it.next(), Some(&1)); - /// assert!(it.next().is_none()); + /// let a1 = [1, 2, 3]; + /// let a2 = [4, 5, 6]; + /// + /// let mut iter = a1.iter().chain(a2.iter()); + /// + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), Some(&4)); + /// assert_eq!(iter.next(), Some(&5)); + /// assert_eq!(iter.next(), Some(&6)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// Since the argument to `chain()` uses [`IntoIterator`], we can pass + /// anything that can be converted into an [`Iterator`], not just an + /// [`Iterator`] itself. For example, slices (`&[T]`) implement + /// [`IntoIterator`], and so can be passed to `chain()` directly: + /// + /// [`IntoIterator`]: trait.IntoIterator.html + /// [`Iterator`]: trait.Iterator.html + /// + /// ``` + /// let s1 = &[1, 2, 3]; + /// let s2 = &[4, 5, 6]; + /// + /// let mut iter = s1.iter().chain(s2); + /// + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), Some(&4)); + /// assert_eq!(iter.next(), Some(&5)); + /// assert_eq!(iter.next(), Some(&6)); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -436,34 +579,73 @@ pub trait Iterator { Chain{a: self, b: other.into_iter(), state: ChainState::Both} } - /// Creates an iterator that iterates over both this and the specified - /// iterators simultaneously, yielding the two elements as pairs. When - /// either iterator returns `None`, all further invocations of `next()` + /// 'Zips up' two iterators into a single iterator of pairs. + /// + /// `zip()` returns a new iterator that will iterate over two other + /// iterators, returning a tuple where the first element comes from the + /// first iterator, and the second element comes from the second iterator. + /// + /// In other words, it zips two iterators together, into a single one. 🤐 + /// + /// When either iterator returns `None`, all further calls to `next()` /// will return `None`. /// /// # Examples /// - /// ``` - /// let a = [0]; - /// let b = [1]; - /// let mut it = a.iter().zip(&b); - /// assert_eq!(it.next(), Some((&0, &1))); - /// assert!(it.next().is_none()); - /// ``` - /// - /// `zip` can provide similar functionality to `enumerate`: + /// Basic usage: /// /// ``` - /// for pair in "foo".chars().enumerate() { - /// println!("{:?}", pair); - /// } + /// let a1 = [1, 2, 3]; + /// let a2 = [4, 5, 6]; /// - /// for pair in (0..).zip("foo".chars()) { - /// println!("{:?}", pair); - /// } + /// let mut iter = a1.iter().zip(a2.iter()); + /// + /// assert_eq!(iter.next(), Some((&1, &4))); + /// assert_eq!(iter.next(), Some((&2, &5))); + /// assert_eq!(iter.next(), Some((&3, &6))); + /// assert_eq!(iter.next(), None); /// ``` /// - /// both produce the same output. + /// Since the argument to `zip()` uses [`IntoIterator`], we can pass + /// anything that can be converted into an [`Iterator`], not just an + /// [`Iterator`] itself. For example, slices (`&[T]`) implement + /// [`IntoIterator`], and so can be passed to `zip()` directly: + /// + /// [`IntoIterator`]: trait.IntoIterator.html + /// [`Iterator`]: trait.Iterator.html + /// + /// ``` + /// let s1 = &[1, 2, 3]; + /// let s2 = &[4, 5, 6]; + /// + /// let mut iter = s1.iter().zip(s2); + /// + /// assert_eq!(iter.next(), Some((&1, &4))); + /// assert_eq!(iter.next(), Some((&2, &5))); + /// assert_eq!(iter.next(), Some((&3, &6))); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// `zip()` is often used to zip an infinite iterator to a finite one. + /// This works because the finite iterator will eventually return `None`, + /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]: + /// + /// ``` + /// let enumerate: Vec<_> = "foo".chars().enumerate().collect(); + /// + /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect(); + /// + /// assert_eq!((0, 'f'), enumerate[0]); + /// assert_eq!((0, 'f'), zipper[0]); + /// + /// assert_eq!((1, 'o'), enumerate[1]); + /// assert_eq!((1, 'o'), zipper[1]); + /// + /// assert_eq!((2, 'o'), enumerate[2]); + /// assert_eq!((2, 'o'), zipper[2]); + /// ``` + /// + /// [`enumerate()`]: trait.Iterator.html#method.enumerate #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn zip(self, other: U) -> Zip where @@ -472,17 +654,52 @@ pub trait Iterator { Zip{a: self, b: other.into_iter()} } - /// Creates a new iterator that will apply the specified function to each - /// element returned by the first, yielding the mapped element instead. + /// Takes a closure and creates an iterator which calls that closure on each + /// element. + /// + /// `map()` transforms one iterator into another, by means of its argument: + /// something that implements `FnMut`. It produces a new iterator which + /// calls this closure on each element of the original iterator. + /// + /// If you are good at thinking in types, you can think of `map()` like this: + /// If you have an iterator that gives you elements of some type `A`, and + /// you want an iterator of some other type `B`, you can use `map()`, + /// passing a closure that takes an `A` and returns a `B`. + /// + /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is + /// lazy, it is best used when you're already working with other iterators. + /// If you're doing some sort of looping for a side effect, it's considered + /// more idiomatic to use [`for`] than `map()`. + /// + /// [`for`]: ../../book/loops.html#for /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2]; - /// let mut it = a.iter().map(|&x| 2 * x); - /// assert_eq!(it.next(), Some(2)); - /// assert_eq!(it.next(), Some(4)); - /// assert!(it.next().is_none()); + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.into_iter().map(|x| 2 * x); + /// + /// assert_eq!(iter.next(), Some(2)); + /// assert_eq!(iter.next(), Some(4)); + /// assert_eq!(iter.next(), Some(6)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// If you're doing some sort of side effect, prefer [`for`] to `map()`: + /// + /// ``` + /// // don't do this: + /// (0..5).map(|x| println!("{}", x)); + /// + /// // it won't even execute, as it is lazy. Rust will warn you about this. + /// + /// // Instead, use for: + /// for x in 0..5 { + /// println!("{}", x); + /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -492,18 +709,66 @@ pub trait Iterator { Map{iter: self, f: f} } - /// Creates an iterator that applies the predicate to each element returned - /// by this iterator. The only elements that will be yielded are those that - /// make the predicate evaluate to `true`. + /// Creates an iterator which uses a closure to determine if an element + /// should be yielded. + /// + /// The closure must return `true` or `false`. `filter()` creates an + /// iterator which calls this closure on each element. If the closure + /// returns `true`, then the element is returned. If the closure returns + /// `false`, it will try again, and call the closure on the next element, + /// seeing if it passes the test. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2]; - /// let mut it = a.iter().filter(|&x| *x > 1); - /// assert_eq!(it.next(), Some(&2)); - /// assert!(it.next().is_none()); + /// let a = [0i32, 1, 2]; + /// + /// let mut iter = a.into_iter().filter(|x| x.is_positive()); + /// + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), None); /// ``` + /// + /// Because the closure passed to `filter()` takes a reference, and many + /// iterators iterate over references, this leads to a possibly confusing + /// situation, where the type of the closure is a double reference: + /// + /// ``` + /// let a = [0, 1, 2]; + /// + /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s! + /// + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// It's common to instead use destructuring on the argument to strip away + /// one: + /// + /// ``` + /// let a = [0, 1, 2]; + /// + /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and * + /// + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// or both: + /// + /// ``` + /// let a = [0, 1, 2]; + /// + /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s + /// + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// of these layers. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn filter

(self, predicate: P) -> Filter where @@ -512,18 +777,57 @@ pub trait Iterator { Filter{iter: self, predicate: predicate} } - /// Creates an iterator that both filters and maps elements. - /// If the specified function returns `None`, the element is skipped. - /// Otherwise the option is unwrapped and the new value is yielded. + /// Creates an iterator that both filters and maps. + /// + /// The closure must return an [`Option`]. `filter_map()` creates an + /// iterator which calls this closure on each element. If the closure + /// returns `Some(element)`, then that element is returned. If the + /// closure returns `None`, it will try again, and call the closure on the + /// next element, seeing if it will return `Some`. + /// + /// [`Option`]: ../option/enum.Option.html + /// + /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this + /// part: + /// + /// [`filter()`]: #method.filter + /// [`map()`]: #method.map + /// + /// > If the closure returns `Some(element)`, then that element is returned. + /// + /// In other words, it removes the [`Option`] layer automatically. If your + /// mapping is already returning an [`Option`] and you want to skip over + /// `None`s, then `filter_map()` is much, much nicer to use. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2]; - /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); - /// assert_eq!(it.next(), Some(4)); - /// assert!(it.next().is_none()); + /// let a = ["1", "2", "lol"]; + /// + /// let mut iter = a.iter().filter_map(|s| s.parse().ok()); + /// + /// assert_eq!(iter.next(), Some(1)); + /// assert_eq!(iter.next(), Some(2)); + /// assert_eq!(iter.next(), None); /// ``` + /// + /// Here's the same example, but with [`filter()`] and [`map()`]: + /// + /// ``` + /// let a = ["1", "2", "lol"]; + /// + /// let mut iter = a.iter() + /// .map(|s| s.parse().ok()) + /// .filter(|s| s.is_some()); + /// + /// assert_eq!(iter.next(), Some(Some(1))); + /// assert_eq!(iter.next(), Some(Some(2))); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// There's an extra layer of `Some` in there. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn filter_map(self, f: F) -> FilterMap where @@ -532,20 +836,28 @@ pub trait Iterator { FilterMap { iter: self, f: f } } - /// Creates an iterator that yields pairs `(i, val)` where `i` is the + /// Creates an iterator which gives the current iteration count as well as + /// the next value. + /// + /// The iterator returned yields pairs `(i, val)`, where `i` is the /// current index of iteration and `val` is the value returned by the /// iterator. /// - /// `enumerate` keeps its count as a `usize`. If you want to count by a - /// different sized integer, the `zip` function provides similar + /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a + /// different sized integer, the [`zip()`] function provides similar /// functionality. /// + /// [`usize`]: ../primitive.usize.html + /// [`zip()`]: #method.zip + /// /// # Overflow Behavior /// /// The method does no guarding against overflows, so enumerating more than - /// `usize::MAX` elements either produces the wrong result or panics. If + /// [`usize::MAX`] elements either produces the wrong result or panics. If /// debug assertions are enabled, a panic is guaranteed. /// + /// [`usize::MAX`]: ../usize/constant.MAX.html + /// /// # Panics /// /// The returned iterator might panic if the to-be-returned index would @@ -554,11 +866,14 @@ pub trait Iterator { /// # Examples /// /// ``` - /// let a = [100, 200]; - /// let mut it = a.iter().enumerate(); - /// assert_eq!(it.next(), Some((0, &100))); - /// assert_eq!(it.next(), Some((1, &200))); - /// assert!(it.next().is_none()); + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter().enumerate(); + /// + /// assert_eq!(iter.next(), Some((0, &1))); + /// assert_eq!(iter.next(), Some((1, &2))); + /// assert_eq!(iter.next(), Some((2, &3))); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -566,22 +881,38 @@ pub trait Iterator { Enumerate { iter: self, count: 0 } } - /// Creates an iterator that has a `.peek()` method - /// that returns an optional reference to the next element. + /// Creates an iterator which can look at the `next()` element without + /// consuming it. + /// + /// Adds a [`peek()`] method to an iterator. See its documentation for + /// more information. + /// + /// [`peek()`]: struct.Peekable.html#method.peek /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let xs = [100, 200, 300]; - /// let mut it = xs.iter().cloned().peekable(); - /// assert_eq!(*it.peek().unwrap(), 100); - /// assert_eq!(it.next().unwrap(), 100); - /// assert_eq!(it.next().unwrap(), 200); - /// assert_eq!(*it.peek().unwrap(), 300); - /// assert_eq!(*it.peek().unwrap(), 300); - /// assert_eq!(it.next().unwrap(), 300); - /// assert!(it.peek().is_none()); - /// assert!(it.next().is_none()); + /// let xs = [1, 2, 3]; + /// + /// let mut iter = xs.iter().peekable(); + /// + /// // peek() lets us see into the future + /// assert_eq!(iter.peek(), Some(&&1)); + /// assert_eq!(iter.next(), Some(&1)); + /// + /// assert_eq!(iter.next(), Some(&2)); + /// + /// // we can peek() multiple times, the itererator won't advance + /// assert_eq!(iter.peek(), Some(&&3)); + /// assert_eq!(iter.peek(), Some(&&3)); + /// + /// assert_eq!(iter.next(), Some(&3)); + /// + /// // after the itererator is finished, so is peek() + /// assert_eq!(iter.peek(), None); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -589,19 +920,60 @@ pub trait Iterator { Peekable{iter: self, peeked: None} } - /// Creates an iterator that invokes the predicate on elements - /// until it returns false. Once the predicate returns false, that - /// element and all further elements are yielded. + /// Creates an iterator that [`skip()`]s elements based on a predicate. + /// + /// [`skip()`]: #method.skip + /// + /// `skip_while()` takes a closure as an argument. It will call this + /// closure on each element of the iterator, and ignore elements + /// until it returns `false`. + /// + /// After `false` is returned, `skip_while()`'s job is over, and the + /// rest of the elements are yielded. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter().skip_while(|&a| *a < 3); - /// assert_eq!(it.next(), Some(&3)); - /// assert_eq!(it.next(), Some(&4)); - /// assert_eq!(it.next(), Some(&5)); - /// assert!(it.next().is_none()); + /// let a = [-1i32, 0, 1]; + /// + /// let mut iter = a.into_iter().skip_while(|x| x.is_negative()); + /// + /// assert_eq!(iter.next(), Some(&0)); + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// Because the closure passed to `skip_while()` takes a reference, and many + /// iterators iterate over references, this leads to a possibly confusing + /// situation, where the type of the closure is a double reference: + /// + /// ``` + /// let a = [-1, 0, 1]; + /// + /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s! + /// + /// assert_eq!(iter.next(), Some(&0)); + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// Stopping after an initial `false`: + /// + /// ``` + /// let a = [-1, 0, 1, -2]; + /// + /// let mut iter = a.into_iter().skip_while(|x| **x < 0); + /// + /// assert_eq!(iter.next(), Some(&0)); + /// assert_eq!(iter.next(), Some(&1)); + /// + /// // while this would have been false, since we already got a false, + /// // skip_while() isn't used any more + /// assert_eq!(iter.next(), Some(&-2)); + /// + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -611,18 +983,53 @@ pub trait Iterator { SkipWhile{iter: self, flag: false, predicate: predicate} } - /// Creates an iterator that yields elements so long as the predicate - /// returns true. After the predicate returns false for the first time, no - /// further elements will be yielded. + /// Creates an iterator that yields elements based on a predicate. + /// + /// `take_while()` takes a closure as an argument. It will call this + /// closure on each element of the iterator, and yield elements + /// while it returns `true`. + /// + /// After `false` is returned, `take_while()`'s job is over, and the + /// rest of the elements are ignored. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter().take_while(|&a| *a < 3); - /// assert_eq!(it.next(), Some(&1)); - /// assert_eq!(it.next(), Some(&2)); - /// assert!(it.next().is_none()); + /// let a = [-1i32, 0, 1]; + /// + /// let mut iter = a.into_iter().take_while(|x| x.is_negative()); + /// + /// assert_eq!(iter.next(), Some(&-1)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// Because the closure passed to `take_while()` takes a reference, and many + /// iterators iterate over references, this leads to a possibly confusing + /// situation, where the type of the closure is a double reference: + /// + /// ``` + /// let a = [-1, 0, 1]; + /// + /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s! + /// + /// assert_eq!(iter.next(), Some(&-1)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// Stopping after an initial `false`: + /// + /// ``` + /// let a = [-1, 0, 1, -2]; + /// + /// let mut iter = a.into_iter().take_while(|x| **x < 0); + /// + /// assert_eq!(iter.next(), Some(&-1)); + /// + /// // We have more elements that are less than zero, but since we already + /// // got a false, take_while() isn't used any more + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -632,17 +1039,21 @@ pub trait Iterator { TakeWhile{iter: self, flag: false, predicate: predicate} } - /// Creates an iterator that skips the first `n` elements of this iterator, - /// and then yields all further items. + /// Creates an iterator that skips the first `n` elements. + /// + /// After they have been consumed, the rest of the elements are yielded. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter().skip(3); - /// assert_eq!(it.next(), Some(&4)); - /// assert_eq!(it.next(), Some(&5)); - /// assert!(it.next().is_none()); + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter().skip(2); + /// + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -650,18 +1061,31 @@ pub trait Iterator { Skip{iter: self, n: n} } - /// Creates an iterator that yields the first `n` elements of this - /// iterator. + /// Creates an iterator that yields its first `n` elements. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter().take(3); - /// assert_eq!(it.next(), Some(&1)); - /// assert_eq!(it.next(), Some(&2)); - /// assert_eq!(it.next(), Some(&3)); - /// assert!(it.next().is_none()); + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter().take(2); + /// + /// assert_eq!(iter.next(), Some(&1)); + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), None); + /// ``` + /// + /// `take()` is often used with an infinite iterator, to make it finite: + /// + /// ``` + /// let mut iter = (0..).take(3); + /// + /// assert_eq!(iter.next(), Some(0)); + /// assert_eq!(iter.next(), Some(1)); + /// assert_eq!(iter.next(), Some(2)); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -669,25 +1093,36 @@ pub trait Iterator { Take{iter: self, n: n} } - /// Creates a new iterator that behaves in a similar fashion to fold. - /// There is a state which is passed between each iteration and can be - /// mutated as necessary. The yielded values from the closure are yielded - /// from the Scan instance when not `None`. + /// An iterator similar to `fold()`, with internal state. + /// + /// `scan()` accumulates a final value, similar to [`fold()`], but instead + /// of passing along an accumulator, it maintains the accumulator internally. + /// + /// [`fold()`]: #method.fold + /// + /// On each iteraton of `scan()`, you can assign to the internal state, and + /// a mutable reference to the state is passed as the first argument to the + /// closure, allowing you to modify it on each iteration. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter().scan(1, |fac, &x| { - /// *fac = *fac * x; - /// Some(*fac) + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter().scan(1, |state, &x| { + /// // each iteration, we'll multiply the state by the element + /// *state = *state * x; + /// + /// // the value passed on to the next iteration + /// Some(*state) /// }); - /// assert_eq!(it.next(), Some(1)); - /// assert_eq!(it.next(), Some(2)); - /// assert_eq!(it.next(), Some(6)); - /// assert_eq!(it.next(), Some(24)); - /// assert_eq!(it.next(), Some(120)); - /// assert!(it.next().is_none()); + /// + /// assert_eq!(iter.next(), Some(1)); + /// assert_eq!(iter.next(), Some(2)); + /// assert_eq!(iter.next(), Some(6)); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -697,15 +1132,27 @@ pub trait Iterator { Scan{iter: self, f: f, state: initial_state} } - /// Takes a function that maps each element to a new iterator and yields - /// all the elements of the produced iterators. + /// Creates an iterator that works like map, but flattens nested structure. /// - /// This is useful for unraveling nested structures. + /// The [`map()`] adapter is very useful, but only when the closure + /// argument produces values. If it produces an iterator instead, there's + /// an extra layer of indirection. `flat_map()` will remove this extra layer + /// on its own. + /// + /// [`map()`]: #method.map + /// + /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns + /// one item for each element, and `flat_map()`'s closure returns an + /// iterator for each element. /// /// # Examples /// + /// Basic usage: + /// /// ``` /// let words = ["alpha", "beta", "gamma"]; + /// + /// // chars() returns an iterator /// let merged: String = words.iter() /// .flat_map(|s| s.chars()) /// .collect(); @@ -719,32 +1166,56 @@ pub trait Iterator { FlatMap{iter: self, f: f, frontiter: None, backiter: None } } - /// Creates an iterator that yields `None` forever after the underlying - /// iterator yields `None`. Random-access iterator behavior is not - /// affected, only single and double-ended iterator behavior. + /// Creates an iterator which ends after the first `None`. + /// + /// After an iterator returns `None`, future calls may or may not yield + /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a + /// `None` is given, it will always return `None` forever. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// fn process>(it: U) -> i32 { - /// let mut it = it.fuse(); - /// let mut sum = 0; - /// for x in it.by_ref() { - /// if x > 5 { - /// break; - /// } - /// sum += x; - /// } - /// // did we exhaust the iterator? - /// if it.next().is_none() { - /// sum += 1000; - /// } - /// sum + /// // an iterator which alternates between Some and None + /// struct Alternate { + /// state: i32, /// } - /// let x = vec![1, 2, 3, 7, 8, 9]; - /// assert_eq!(process(x.into_iter()), 6); - /// let x = vec![1, 2, 3]; - /// assert_eq!(process(x.into_iter()), 1006); + /// + /// impl Iterator for Alternate { + /// type Item = i32; + /// + /// fn next(&mut self) -> Option { + /// let val = self.state; + /// self.state = self.state + 1; + /// + /// // if it's even, Some(i32), else None + /// if val % 2 == 0 { + /// Some(val) + /// } else { + /// None + /// } + /// } + /// } + /// + /// let mut iter = Alternate { state: 0 }; + /// + /// // we can see our iterator going back and forth + /// assert_eq!(iter.next(), Some(0)); + /// assert_eq!(iter.next(), None); + /// assert_eq!(iter.next(), Some(2)); + /// assert_eq!(iter.next(), None); + /// + /// // however, once we fuse it... + /// let mut iter = iter.fuse(); + /// + /// assert_eq!(iter.next(), Some(4)); + /// assert_eq!(iter.next(), None); + /// + /// // it will always return None after the first time. + /// assert_eq!(iter.next(), None); + /// assert_eq!(iter.next(), None); + /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -752,21 +1223,52 @@ pub trait Iterator { Fuse{iter: self, done: false} } - /// Creates an iterator that calls a function with a reference to each - /// element before yielding it. This is often useful for debugging an - /// iterator pipeline. + /// Do something with each element of an iterator, passing the value on. + /// + /// When using iterators, you'll often chain several of them together. + /// While working on such code, you might want to check out what's + /// happening at various parts in the pipeline. To do that, insert + /// a call to `inspect()`. + /// + /// It's much more common for `inspect()` to be used as a debugging tool + /// than to exist in your final code, but never say never. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 4, 2, 3, 8, 9, 6]; - /// let sum: i32 = a.iter() - /// .map(|x| *x) - /// .inspect(|&x| println!("filtering {}", x)) - /// .filter(|&x| x % 2 == 0) - /// .inspect(|&x| println!("{} made it through", x)) - /// .fold(0, |sum, i| sum + i); + /// let a = [1, 4, 2, 3]; + /// + /// // this iterator sequence is complex. + /// let sum = a.iter() + /// .cloned() + /// .filter(|&x| x % 2 == 0) + /// .fold(0, |sum, i| sum + i); + /// /// println!("{}", sum); + /// + /// // let's add some inspect() calls to investigate what's happening + /// let sum = a.iter() + /// .cloned() + /// .inspect(|x| println!("about to filter: {}", x)) + /// .filter(|&x| x % 2 == 0) + /// .inspect(|x| println!("made it through filter: {}", x)) + /// .fold(0, |sum, i| sum + i); + /// + /// println!("{}", sum); + /// ``` + /// + /// This will print: + /// + /// ```text + /// about to filter: 1 + /// about to filter: 4 + /// made it through filter: 4 + /// about to filter: 2 + /// made it through filter: 2 + /// about to filter: 3 + /// 6 /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -776,32 +1278,162 @@ pub trait Iterator { Inspect{iter: self, f: f} } - /// Creates a wrapper around a mutable reference to the iterator. + /// Borrows an iterator, rather than consuming it. /// /// This is useful to allow applying iterator adaptors while still - /// retaining ownership of the original iterator value. + /// retaining ownership of the original iterator. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let mut it = 0..10; - /// // sum the first five values - /// let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b); - /// assert_eq!(partial_sum, 10); - /// assert_eq!(it.next(), Some(5)); + /// let a = [1, 2, 3]; + /// + /// let iter = a.into_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's try that again + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.into_iter(); + /// + /// // 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); + /// + /// // now this is just fine: + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn by_ref(&mut self) -> &mut Self where Self: Sized { self } - /// Loops through the entire iterator, collecting all of the elements into - /// a container implementing `FromIterator`. + /// Transforms an iterator into a collection. + /// + /// `collect()` can take anything iterable, and turn it into a relevant + /// collection. This is one of the more powerful methods in the standard + /// library, used in a variety of contexts. + /// + /// The most basic pattern in which `collect()` is used is to turn one + /// collection into another. You take a collection, call `iter()` on it, + /// do a bunch of transformations, and then `collect()` at the end. + /// + /// One of the keys to `collect()`'s power is that many things you might + /// not think of as 'collections' actually are. For example, a [`String`] + /// is a collection of [`char`]s. And a collection of [`Result`] can + /// be thought of as single [`Result, E>`]. See the examples + /// below for more. + /// + /// [`String`]: ../string/struct.String.html + /// [`Result`]: ../result/enum.Result.html + /// [`char`]: ../primitive.char.html + /// + /// Because `collect()` is so general, it can cause problems with type + /// inference. As such, `collect()` is one of the few times you'll see + /// the syntax affectionately known as the 'turbofish': `::<>`. This + /// helps the inference algorithm understand specifically which collection + /// you're trying to collect into. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let expected = [1, 2, 3, 4, 5]; - /// let actual: Vec<_> = expected.iter().cloned().collect(); - /// assert_eq!(actual, expected); + /// let a = [1, 2, 3]; + /// + /// let doubled: Vec = a.iter() + /// .map(|&x| x * 2) + /// .collect(); + /// + /// assert_eq!(vec![2, 4, 6], doubled); + /// ``` + /// + /// Note that we needed the `: Vec` on the left-hand side. This is because + /// we could collect into, for example, a [`VecDeque`] instead: + /// + /// [`VecDeque`]: ../collections/struct.VecDeque.html + /// + /// ``` + /// use std::collections::VecDeque; + /// + /// let a = [1, 2, 3]; + /// + /// let doubled: VecDeque = a.iter() + /// .map(|&x| x * 2) + /// .collect(); + /// + /// assert_eq!(2, doubled[0]); + /// assert_eq!(4, doubled[1]); + /// assert_eq!(6, doubled[2]); + /// ``` + /// + /// Using the 'turbofish' instead of annotationg `doubled`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let doubled = a.iter() + /// .map(|&x| x * 2) + /// .collect::>(); + /// + /// assert_eq!(vec![2, 4, 6], doubled); + /// ``` + /// + /// Because `collect()` cares about what you're collecting into, you can + /// still use a partial type hint, `_`, with the turbofish: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let doubled = a.iter() + /// .map(|&x| x * 2) + /// .collect::>(); + /// + /// assert_eq!(vec![2, 4, 6], doubled); + /// ``` + /// + /// Using `collect()` to make a [`String`]: + /// + /// ``` + /// let chars = ['g', 'd', 'k', 'k', 'n']; + /// + /// let hello: String = chars.iter() + /// .map(|&x| x as u8) + /// .map(|x| (x + 1) as char) + /// .collect(); + /// + /// assert_eq!("hello", hello); + /// ``` + /// + /// If you have a list of [`Result`]s, you can use `collect()` to + /// see if any of them failed: + /// + /// ``` + /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")]; + /// + /// let result: Result, &str> = results.iter().cloned().collect(); + /// + /// // gives us the first error + /// assert_eq!(Err("nope"), result); + /// + /// let results = [Ok(1), Ok(3)]; + /// + /// let result: Result, &str> = results.iter().cloned().collect(); + /// + /// // gives us the list of answers + /// assert_eq!(Ok(vec![1, 3]), result); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -809,16 +1441,24 @@ pub trait Iterator { FromIterator::from_iter(self) } - /// Loops through the entire iterator, collecting all of the elements into - /// one of two containers, depending on a predicate. The elements of the - /// first container satisfy the predicate, while the elements of the second - /// do not. + /// Consumes an iterator, creating two collections from it. + /// + /// The predicate passed to `partition()` can return `true`, or `false`. + /// `partition()` returns a pair, all of the elements for which it returned + /// `true`, and all of the elements for which it returned `false`. + /// + /// # Examples + /// + /// Basic usage: /// /// ``` - /// let vec = vec![1, 2, 3, 4]; - /// let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0); - /// assert_eq!(even, [2, 4]); - /// assert_eq!(odd, [1, 3]); + /// let a = [1, 2, 3]; + /// + /// let (even, odd): (Vec, Vec) = a.into_iter() + /// .partition(|&n| n % 2 == 0); + /// + /// assert_eq!(even, vec![2]); + /// assert_eq!(odd, vec![1, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn partition(self, mut f: F) -> (B, B) where @@ -840,16 +1480,67 @@ pub trait Iterator { (left, right) } - /// Performs a fold operation over the entire iterator, returning the - /// eventual state at the end of the iteration. + /// An iterator adaptor that applies a function, producing a single, final value. + /// + /// `fold()` takes two arguments: an initial value, and a closure with two + /// arguments: an 'accumulator', and an element. It returns the value that + /// the accumulator should have for the next iteration. + /// + /// The initial value is the value the accumulator will have on the first + /// call. + /// + /// After applying this closure to every element of the iterator, `fold()` + /// returns the accumulator. /// /// This operation is sometimes called 'reduce' or 'inject'. /// + /// Folding is useful whenever you have a collection of something, and want + /// to produce a single value from it. + /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// assert_eq!(a.iter().fold(0, |acc, &item| acc + item), 15); + /// let a = [1, 2, 3]; + /// + /// // the sum of all of the elements of a + /// let sum = a.iter() + /// .fold(0, |acc, &x| acc + x); + /// + /// assert_eq!(sum, 6); + /// ``` + /// + /// Let's walk through each step of the iteration here: + /// + /// | element | acc | x | result | + /// |---------|-----|---|--------| + /// | | 0 | | | + /// | 1 | 0 | 1 | 1 | + /// | 2 | 1 | 2 | 3 | + /// | 3 | 3 | 3 | 6 | + /// + /// And so, our final result, `6`. + /// + /// It's common for people who haven't used iterators a lot to + /// use a `for` loop with a list of things to build up a result. Those + /// can be turned into `fold()`s: + /// + /// ``` + /// let numbers = [1, 2, 3, 4, 5]; + /// + /// let mut result = 0; + /// + /// // for loop: + /// for i in &numbers { + /// result = result + i; + /// } + /// + /// // fold: + /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x); + /// + /// // they're the same + /// assert_eq!(result, result2); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -863,16 +1554,40 @@ pub trait Iterator { accum } - /// Tests whether the predicate holds true for all elements in the iterator. + /// Tests if every element of the iterator matches a predicate. /// - /// Does not consume the iterator past the first non-matching element. + /// `all()` takes a closure that returns `true` or `false`. It applies + /// this closure to each element of the iterator, and if they all return + /// `true`, then so does `all()`. If any of them return `false`, it + /// returns `false`. + /// + /// `all()` is short-circuting; in other words, it will stop processing + /// as soon as it finds a `false`, given that no matter what else happens, + /// the result will also be `false`. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// assert!(a.iter().all(|x| *x > 0)); - /// assert!(!a.iter().all(|x| *x > 2)); + /// let a = [1, 2, 3]; + /// + /// assert!(a.iter().all(|&x| x > 0)); + /// + /// assert!(!a.iter().all(|&x| x > 2)); + /// ``` + /// + /// Stopping at the first `false`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert!(!iter.all(|&x| x != 2)); + /// + /// // we can still use `iter`, as there are more elements. + /// assert_eq!(iter.next(), Some(&3)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -887,18 +1602,40 @@ pub trait Iterator { true } - /// Tests whether any element of an iterator satisfies the specified - /// predicate. + /// Tests if any element of the iterator matches a predicate. /// - /// Does not consume the iterator past the first found element. + /// `any()` takes a closure that returns `true` or `false`. It applies + /// this closure to each element of the iterator, and if any of them return + /// `true`, then so does `any()`. If they all return `false`, it + /// returns `false`. + /// + /// `any()` is short-circuting; in other words, it will stop processing + /// as soon as it finds a `true`, given that no matter what else happens, + /// the result will also be `true`. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter(); - /// assert!(it.any(|x| *x == 3)); - /// assert_eq!(it.collect::>(), [&4, &5]); + /// let a = [1, 2, 3]; + /// + /// assert!(a.iter().any(|&x| x > 0)); + /// + /// assert!(!a.iter().any(|&x| x > 5)); + /// ``` + /// + /// Stopping at the first `true`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert!(iter.any(|&x| x != 2)); + /// + /// // we can still use `iter`, as there are more elements. + /// assert_eq!(iter.next(), Some(&2)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -914,17 +1651,45 @@ pub trait Iterator { false } - /// Returns the first element satisfying the specified predicate. + /// Searches for an element of an iterator that satisfies a predicate. /// - /// Does not consume the iterator past the first found element. + /// `find()` takes a closure that returns `true` or `false`. It applies + /// this closure to each element of the iterator, and if any of them return + /// `true`, then `find()` returns `Some(element)`. If they all return + /// `false`, it returns `None`. + /// + /// `find()` is short-circuting; in other words, it will stop processing + /// as soon as the closure returns `true`. + /// + /// Because `find()` takes a reference, and many iterators iterate over + /// references, this leads to a possibly confusing situation where the + /// argument is a double reference. You can see this effect in the + /// examples below, with `&&x`. /// /// # Examples /// + /// Basic usage: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2)); + /// + /// assert_eq!(a.iter().find(|&&x| x == 5), None); + /// ``` + /// + /// Stopping at the first `true`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert_eq!(iter.find(|&&x| x == 2), Some(&2)); + /// + /// // we can still use `iter`, as there are more elements. + /// assert_eq!(iter.next(), Some(&3)); /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter(); - /// assert_eq!(it.find(|&x| *x == 3), Some(&3)); - /// assert_eq!(it.collect::>(), [&4, &5]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn find

(&mut self, mut predicate: P) -> Option where @@ -937,9 +1702,15 @@ pub trait Iterator { None } - /// Returns the index of the first element satisfying the specified predicate + /// Searches for an element in an iterator, returning its index. /// - /// Does not consume the iterator past the first found element. + /// `position()` takes a closure that returns `true` or `false`. It applies + /// this closure to each element of the iterator, and if if one of them + /// returns `true`, then `position()` returns `Some(index)`. If all of + /// them return `false`, it returns `None`. + /// + /// `position()` is short-circuting; in other words, it will stop + /// processing as soon as it finds a `true`. /// /// # Overflow Behavior /// @@ -950,16 +1721,33 @@ pub trait Iterator { /// /// # Panics /// - /// This functions might panic if the iterator has more than `usize::MAX` + /// This function might panic if the iterator has more than `usize::MAX` /// non-matching elements. /// /// # Examples /// + /// Basic usage: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// assert_eq!(a.iter().position(|&x| x == 2), Some(1)); + /// + /// assert_eq!(a.iter().position(|&x| x == 5), None); + /// ``` + /// + /// Stopping at the first `true`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert_eq!(iter.position(|&x| x == 2), Some(1)); + /// + /// // we can still use `iter`, as there are more elements. + /// assert_eq!(iter.next(), Some(&3)); /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// let mut it = a.iter(); - /// assert_eq!(it.position(|x| *x == 3), Some(2)); - /// assert_eq!(it.collect::>(), [&4, &5]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn position

(&mut self, mut predicate: P) -> Option where @@ -975,19 +1763,41 @@ pub trait Iterator { None } - /// Returns the index of the last element satisfying the specified predicate + /// Searches for an element in an iterator from the right, returning its + /// index. /// - /// If no element matches, `None` is returned. + /// `rposition()` takes a closure that returns `true` or `false`. It applies + /// this closure to each element of the iterator, starting from the end, + /// and if if one of them returns `true`, then `rposition()` returns + /// `Some(index)`. If all of them return `false`, it returns `None`. /// - /// Does not consume the iterator *before* the first found element. + /// `rposition()` is short-circuting; in other words, it will stop + /// processing as soon as it finds a `true`. /// /// # Examples /// + /// Basic usage: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2)); + /// + /// assert_eq!(a.iter().rposition(|&x| x == 5), None); + /// ``` + /// + /// Stopping at the first `true`: + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter(); + /// + /// assert_eq!(iter.rposition(|&x| x == 2), Some(1)); + /// + /// // we can still use `iter`, as there are more elements. + /// assert_eq!(iter.next(), Some(&1)); /// ``` - /// let a = [1, 2, 2, 4, 5]; - /// let mut it = a.iter(); - /// assert_eq!(it.rposition(|x| *x == 2), Some(2)); - /// assert_eq!(it.collect::>(), [&1, &2]); #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn rposition

(&mut self, mut predicate: P) -> Option where @@ -1007,16 +1817,19 @@ pub trait Iterator { None } - /// Consumes the entire iterator to return the maximum element. + /// Returns the maximum element of an iterator. /// - /// Returns the rightmost element if the comparison determines two elements - /// to be equally maximum. + /// If the two elements are equally maximum, the latest element is + /// returned. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; - /// assert_eq!(a.iter().max(), Some(&5)); + /// let a = [1, 2, 3]; + /// + /// assert_eq!(a.iter().max(), Some(&3)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -1030,15 +1843,18 @@ pub trait Iterator { .map(|(_, x)| x) } - /// Consumes the entire iterator to return the minimum element. + /// Returns the minimum element of an iterator. /// - /// Returns the leftmost element if the comparison determines two elements - /// to be equally minimum. + /// If the two elements are equally minimum, the first element is + /// returned. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1, 2, 3]; + /// /// assert_eq!(a.iter().min(), Some(&1)); /// ``` #[inline] @@ -1086,7 +1902,7 @@ pub trait Iterator { /// Returns the element that gives the minimum value from the /// specified function. /// - /// Returns the leftmost element if the comparison determines two elements + /// Returns the latest element if the comparison determines two elements /// to be equally minimum. /// /// # Examples @@ -1113,18 +1929,29 @@ pub trait Iterator { .map(|(_, x)| x) } - /// Change the direction of the iterator + /// Reverses an iterator's direction. /// - /// The flipped iterator swaps the ends on an iterator that can already - /// be iterated from the front and from the back. + /// Usually, iterators iterate from left to right. After using `rev()`, + /// an iterator will instead iterate from right to left. /// + /// This is only possible if the iterator has an end, so `rev()` only + /// works on [`DoubleEndedIterator`]s. /// - /// If the iterator also implements RandomAccessIterator, the flipped - /// iterator is also random access, with the indices starting at the back - /// of the original iterator. + /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html /// - /// Note: Random access with flipped indices still only applies to the first - /// `std::usize::MAX` elements of the original iterator. + /// # Examples + /// + /// ``` + /// let a = [1, 2, 3]; + /// + /// let mut iter = a.iter().rev(); + /// + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), Some(&1)); + /// + /// assert_eq!(iter.next(), None); + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn rev(self) -> Rev where Self: Sized + DoubleEndedIterator { @@ -1133,14 +1960,23 @@ pub trait Iterator { /// Converts an iterator of pairs into a pair of containers. /// - /// Loops through the entire iterator, collecting the first component of - /// each item into one new container, and the second component into another. + /// `unzip()` consumes an entire iterator of pairs, producing two + /// collections: one from the left elements of the pairs, and one + /// from the right elements. + /// + /// This function is, in some sense, the opposite of [`zip()`]. + /// + /// [`zip()`]: #method.zip /// /// # Examples /// + /// Basic usage: + /// /// ``` /// let a = [(1, 2), (3, 4)]; + /// /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip(); + /// /// assert_eq!(left, [1, 3]); /// assert_eq!(right, [2, 4]); /// ``` @@ -1175,18 +2011,25 @@ pub trait Iterator { (ts, us) } - /// Creates an iterator that clones the elements it yields. + /// Creates an iterator which clone()s all of its elements. /// - /// This is useful for converting an `Iterator<&T>` to an`Iterator`, - /// so it's a more convenient form of `map(|&x| x)`. + /// This is useful when you have an iterator over `&T`, but you need an + /// iterator over `T`. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [0, 1, 2]; + /// let a = [1, 2, 3]; + /// /// let v_cloned: Vec<_> = a.iter().cloned().collect(); + /// + /// // cloned is the same as .map(|&x| x), for integers /// let v_map: Vec<_> = a.iter().map(|&x| x).collect(); - /// assert_eq!(v_cloned, v_map); + /// + /// assert_eq!(v_cloned, vec![1, 2, 3]); + /// assert_eq!(v_map, vec![1, 2, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn cloned<'a, T: 'a>(self) -> Cloned @@ -1195,15 +2038,27 @@ pub trait Iterator { Cloned { it: self } } - /// Repeats an iterator endlessly + /// Repeats an iterator endlessly. + /// + /// Instead of stopping at `None`, the iterator will instead start again, + /// from the beginning. After iterating again, it will start at the + /// beginning again. And again. And again. Forever. /// /// # Examples /// + /// Basic usage: + /// /// ``` - /// let a = [1, 2]; + /// let a = [1, 2, 3]; + /// /// let mut it = a.iter().cycle(); + /// /// assert_eq!(it.next(), Some(&1)); /// assert_eq!(it.next(), Some(&2)); + /// assert_eq!(it.next(), Some(&3)); + /// assert_eq!(it.next(), Some(&1)); + /// assert_eq!(it.next(), Some(&2)); + /// assert_eq!(it.next(), Some(&3)); /// assert_eq!(it.next(), Some(&1)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1212,16 +2067,21 @@ pub trait Iterator { Cycle{orig: self.clone(), iter: self} } - /// Iterates over the entire iterator, summing up all the elements + /// Sums the elements of an iterator. + /// + /// Takes each element, adds them together, and returns the result. /// /// # Examples /// + /// Basic usage: + /// /// ``` /// #![feature(iter_arith)] /// - /// let a = [1, 2, 3, 4, 5]; - /// let it = a.iter(); - /// assert_eq!(it.sum::(), 15); + /// let a = [1, 2, 3]; + /// let sum: i32 = a.iter().sum(); + /// + /// assert_eq!(sum, 6); /// ``` #[unstable(feature = "iter_arith", reason = "bounds recently changed", issue = "27739")] @@ -2520,8 +3380,45 @@ impl ExactSizeIterator for Peekable {} #[stable(feature = "rust1", since = "1.0.0")] impl Peekable { - /// Returns a reference to the next element of the iterator with out - /// advancing it, or None if the iterator is exhausted. + /// Returns a reference to the next() value without advancing the iterator. + /// + /// The `peek()` method will return the value that a call to [`next()`] would + /// return, but does not advance the iterator. Like [`next()`], if there is + /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it + /// will return `None`. + /// + /// [`next()`]: trait.Iterator.html#tymethod.next + /// + /// Because `peek()` returns reference, and many iterators iterate over + /// references, this leads to a possibly confusing situation where the + /// return value is a double reference. You can see this effect in the + /// examples below, with `&&i32`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// let xs = [1, 2, 3]; + /// + /// let mut iter = xs.iter().peekable(); + /// + /// // peek() lets us see into the future + /// assert_eq!(iter.peek(), Some(&&1)); + /// assert_eq!(iter.next(), Some(&1)); + /// + /// assert_eq!(iter.next(), Some(&2)); + /// + /// // we can peek() multiple times, the itererator won't advance + /// assert_eq!(iter.peek(), Some(&&3)); + /// assert_eq!(iter.peek(), Some(&&3)); + /// + /// assert_eq!(iter.next(), Some(&3)); + /// + /// // after the itererator is finished, so is peek() + /// assert_eq!(iter.peek(), None); + /// assert_eq!(iter.next(), None); + /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn peek(&mut self) -> Option<&I::Item> { @@ -2534,7 +3431,32 @@ impl Peekable { } } - /// Checks whether peekable iterator is empty or not. + /// Checks if the iterator has finished iterating. + /// + /// Returns `true` if there are no more elements in the iterator, and + /// `false` if there are. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(core)] + /// + /// let xs = [1, 2, 3]; + /// + /// let mut iter = xs.iter().peekable(); + /// + /// // there are still elements to iterate over + /// assert_eq!(iter.is_empty(), false); + /// + /// // let's consume the iterator + /// iter.next(); + /// iter.next(); + /// iter.next(); + /// + /// assert_eq!(iter.is_empty(), true); + /// ``` #[inline] pub fn is_empty(&mut self) -> bool { self.peek().is_none()