1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
15 use option::Option::{self, Some, None};
18 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse};
19 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev};
20 use super::{Zip, Sum, Product};
21 use super::ChainState;
22 use super::{DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator};
23 use super::{IntoIterator, ZipImpl};
25 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
27 /// An interface for dealing with iterators.
29 /// This is the main iterator trait. For more about the concept of iterators
30 /// generally, please see the [module-level documentation]. In particular, you
31 /// may want to know how to [implement `Iterator`][impl].
33 /// [module-level documentation]: index.html
34 /// [impl]: index.html#implementing-iterator
35 #[stable(feature = "rust1", since = "1.0.0")]
36 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
37 `.iter()` or a similar method"]
39 /// The type of the elements being iterated over.
40 #[stable(feature = "rust1", since = "1.0.0")]
43 /// Advances the iterator and returns the next value.
45 /// Returns `None` when iteration is finished. Individual iterator
46 /// implementations may choose to resume iteration, and so calling `next()`
47 /// again may or may not eventually start returning `Some(Item)` again at some
55 /// let a = [1, 2, 3];
57 /// let mut iter = a.iter();
59 /// // A call to next() returns the next value...
60 /// assert_eq!(Some(&1), iter.next());
61 /// assert_eq!(Some(&2), iter.next());
62 /// assert_eq!(Some(&3), iter.next());
64 /// // ... and then None once it's over.
65 /// assert_eq!(None, iter.next());
67 /// // More calls may or may not return None. Here, they always will.
68 /// assert_eq!(None, iter.next());
69 /// assert_eq!(None, iter.next());
71 #[stable(feature = "rust1", since = "1.0.0")]
72 fn next(&mut self) -> Option<Self::Item>;
74 /// Returns the bounds on the remaining length of the iterator.
76 /// Specifically, `size_hint()` returns a tuple where the first element
77 /// is the lower bound, and the second element is the upper bound.
79 /// The second half of the tuple that is returned is an `Option<usize>`. A
80 /// `None` here means that either there is no known upper bound, or the
81 /// upper bound is larger than `usize`.
83 /// # Implementation notes
85 /// It is not enforced that an iterator implementation yields the declared
86 /// number of elements. A buggy iterator may yield less than the lower bound
87 /// or more than the upper bound of elements.
89 /// `size_hint()` is primarily intended to be used for optimizations such as
90 /// reserving space for the elements of the iterator, but must not be
91 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
92 /// implementation of `size_hint()` should not lead to memory safety
95 /// That said, the implementation should provide a correct estimation,
96 /// because otherwise it would be a violation of the trait's protocol.
98 /// The default implementation returns `(0, None)` which is correct for any
106 /// let a = [1, 2, 3];
107 /// let iter = a.iter();
109 /// assert_eq!((3, Some(3)), iter.size_hint());
112 /// A more complex example:
115 /// // The even numbers from zero to ten.
116 /// let iter = (0..10).filter(|x| x % 2 == 0);
118 /// // We might iterate from zero to ten times. Knowing that it's five
119 /// // exactly wouldn't be possible without executing filter().
120 /// assert_eq!((0, Some(10)), iter.size_hint());
122 /// // Let's add one five more numbers with chain()
123 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
125 /// // now both bounds are increased by five
126 /// assert_eq!((5, Some(15)), iter.size_hint());
129 /// Returning `None` for an upper bound:
132 /// // an infinite iterator has no upper bound
135 /// assert_eq!((0, None), iter.size_hint());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
141 /// Consumes the iterator, counting the number of iterations and returning it.
143 /// This method will evaluate the iterator until its [`next()`] returns
144 /// `None`. Once `None` is encountered, `count()` returns the number of
145 /// times it called [`next()`].
147 /// [`next()`]: #tymethod.next
149 /// # Overflow Behavior
151 /// The method does no guarding against overflows, so counting elements of
152 /// an iterator with more than `usize::MAX` elements either produces the
153 /// wrong result or panics. If debug assertions are enabled, a panic is
158 /// This function might panic if the iterator has more than `usize::MAX`
166 /// let a = [1, 2, 3];
167 /// assert_eq!(a.iter().count(), 3);
169 /// let a = [1, 2, 3, 4, 5];
170 /// assert_eq!(a.iter().count(), 5);
173 #[rustc_inherit_overflow_checks]
174 #[stable(feature = "rust1", since = "1.0.0")]
175 fn count(self) -> usize where Self: Sized {
177 self.fold(0, |cnt, _| cnt + 1)
180 /// Consumes the iterator, returning the last element.
182 /// This method will evaluate the iterator until it returns `None`. While
183 /// doing so, it keeps track of the current element. After `None` is
184 /// returned, `last()` will then return the last element it saw.
191 /// let a = [1, 2, 3];
192 /// assert_eq!(a.iter().last(), Some(&3));
194 /// let a = [1, 2, 3, 4, 5];
195 /// assert_eq!(a.iter().last(), Some(&5));
198 #[stable(feature = "rust1", since = "1.0.0")]
199 fn last(self) -> Option<Self::Item> where Self: Sized {
201 for x in self { last = Some(x); }
205 /// Consumes the `n` first elements of the iterator, then returns the
208 /// This method will evaluate the iterator `n` times, discarding those elements.
209 /// After it does so, it will call [`next()`] and return its value.
211 /// [`next()`]: #tymethod.next
213 /// Like most indexing operations, the count starts from zero, so `nth(0)`
214 /// returns the first value, `nth(1)` the second, and so on.
216 /// `nth()` will return `None` if `n` is greater than or equal to the length of the
224 /// let a = [1, 2, 3];
225 /// assert_eq!(a.iter().nth(1), Some(&2));
228 /// Calling `nth()` multiple times doesn't rewind the iterator:
231 /// let a = [1, 2, 3];
233 /// let mut iter = a.iter();
235 /// assert_eq!(iter.nth(1), Some(&2));
236 /// assert_eq!(iter.nth(1), None);
239 /// Returning `None` if there are less than `n + 1` elements:
242 /// let a = [1, 2, 3];
243 /// assert_eq!(a.iter().nth(10), None);
246 #[stable(feature = "rust1", since = "1.0.0")]
247 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
249 if n == 0 { return Some(x) }
255 /// Takes two iterators and creates a new iterator over both in sequence.
257 /// `chain()` will return a new iterator which will first iterate over
258 /// values from the first iterator and then over values from the second
261 /// In other words, it links two iterators together, in a chain. 🔗
268 /// let a1 = [1, 2, 3];
269 /// let a2 = [4, 5, 6];
271 /// let mut iter = a1.iter().chain(a2.iter());
273 /// assert_eq!(iter.next(), Some(&1));
274 /// assert_eq!(iter.next(), Some(&2));
275 /// assert_eq!(iter.next(), Some(&3));
276 /// assert_eq!(iter.next(), Some(&4));
277 /// assert_eq!(iter.next(), Some(&5));
278 /// assert_eq!(iter.next(), Some(&6));
279 /// assert_eq!(iter.next(), None);
282 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
283 /// anything that can be converted into an [`Iterator`], not just an
284 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
285 /// [`IntoIterator`], and so can be passed to `chain()` directly:
287 /// [`IntoIterator`]: trait.IntoIterator.html
288 /// [`Iterator`]: trait.Iterator.html
291 /// let s1 = &[1, 2, 3];
292 /// let s2 = &[4, 5, 6];
294 /// let mut iter = s1.iter().chain(s2);
296 /// assert_eq!(iter.next(), Some(&1));
297 /// assert_eq!(iter.next(), Some(&2));
298 /// assert_eq!(iter.next(), Some(&3));
299 /// assert_eq!(iter.next(), Some(&4));
300 /// assert_eq!(iter.next(), Some(&5));
301 /// assert_eq!(iter.next(), Some(&6));
302 /// assert_eq!(iter.next(), None);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
307 Self: Sized, U: IntoIterator<Item=Self::Item>,
309 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
312 /// 'Zips up' two iterators into a single iterator of pairs.
314 /// `zip()` returns a new iterator that will iterate over two other
315 /// iterators, returning a tuple where the first element comes from the
316 /// first iterator, and the second element comes from the second iterator.
318 /// In other words, it zips two iterators together, into a single one.
320 /// When either iterator returns `None`, all further calls to `next()`
321 /// will return `None`.
328 /// let a1 = [1, 2, 3];
329 /// let a2 = [4, 5, 6];
331 /// let mut iter = a1.iter().zip(a2.iter());
333 /// assert_eq!(iter.next(), Some((&1, &4)));
334 /// assert_eq!(iter.next(), Some((&2, &5)));
335 /// assert_eq!(iter.next(), Some((&3, &6)));
336 /// assert_eq!(iter.next(), None);
339 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
340 /// anything that can be converted into an [`Iterator`], not just an
341 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
342 /// [`IntoIterator`], and so can be passed to `zip()` directly:
344 /// [`IntoIterator`]: trait.IntoIterator.html
345 /// [`Iterator`]: trait.Iterator.html
348 /// let s1 = &[1, 2, 3];
349 /// let s2 = &[4, 5, 6];
351 /// let mut iter = s1.iter().zip(s2);
353 /// assert_eq!(iter.next(), Some((&1, &4)));
354 /// assert_eq!(iter.next(), Some((&2, &5)));
355 /// assert_eq!(iter.next(), Some((&3, &6)));
356 /// assert_eq!(iter.next(), None);
359 /// `zip()` is often used to zip an infinite iterator to a finite one.
360 /// This works because the finite iterator will eventually return `None`,
361 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
364 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
366 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
368 /// assert_eq!((0, 'f'), enumerate[0]);
369 /// assert_eq!((0, 'f'), zipper[0]);
371 /// assert_eq!((1, 'o'), enumerate[1]);
372 /// assert_eq!((1, 'o'), zipper[1]);
374 /// assert_eq!((2, 'o'), enumerate[2]);
375 /// assert_eq!((2, 'o'), zipper[2]);
378 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
380 #[stable(feature = "rust1", since = "1.0.0")]
381 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
382 Self: Sized, U: IntoIterator
384 Zip::new(self, other.into_iter())
387 /// Takes a closure and creates an iterator which calls that closure on each
390 /// `map()` transforms one iterator into another, by means of its argument:
391 /// something that implements `FnMut`. It produces a new iterator which
392 /// calls this closure on each element of the original iterator.
394 /// If you are good at thinking in types, you can think of `map()` like this:
395 /// If you have an iterator that gives you elements of some type `A`, and
396 /// you want an iterator of some other type `B`, you can use `map()`,
397 /// passing a closure that takes an `A` and returns a `B`.
399 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
400 /// lazy, it is best used when you're already working with other iterators.
401 /// If you're doing some sort of looping for a side effect, it's considered
402 /// more idiomatic to use [`for`] than `map()`.
404 /// [`for`]: ../../book/loops.html#for
411 /// let a = [1, 2, 3];
413 /// let mut iter = a.into_iter().map(|x| 2 * x);
415 /// assert_eq!(iter.next(), Some(2));
416 /// assert_eq!(iter.next(), Some(4));
417 /// assert_eq!(iter.next(), Some(6));
418 /// assert_eq!(iter.next(), None);
421 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
424 /// # #![allow(unused_must_use)]
425 /// // don't do this:
426 /// (0..5).map(|x| println!("{}", x));
428 /// // it won't even execute, as it is lazy. Rust will warn you about this.
430 /// // Instead, use for:
432 /// println!("{}", x);
436 #[stable(feature = "rust1", since = "1.0.0")]
437 fn map<B, F>(self, f: F) -> Map<Self, F> where
438 Self: Sized, F: FnMut(Self::Item) -> B,
440 Map{iter: self, f: f}
443 /// Creates an iterator which uses a closure to determine if an element
444 /// should be yielded.
446 /// The closure must return `true` or `false`. `filter()` creates an
447 /// iterator which calls this closure on each element. If the closure
448 /// returns `true`, then the element is returned. If the closure returns
449 /// `false`, it will try again, and call the closure on the next element,
450 /// seeing if it passes the test.
457 /// let a = [0i32, 1, 2];
459 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
461 /// assert_eq!(iter.next(), Some(&1));
462 /// assert_eq!(iter.next(), Some(&2));
463 /// assert_eq!(iter.next(), None);
466 /// Because the closure passed to `filter()` takes a reference, and many
467 /// iterators iterate over references, this leads to a possibly confusing
468 /// situation, where the type of the closure is a double reference:
471 /// let a = [0, 1, 2];
473 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
475 /// assert_eq!(iter.next(), Some(&2));
476 /// assert_eq!(iter.next(), None);
479 /// It's common to instead use destructuring on the argument to strip away
483 /// let a = [0, 1, 2];
485 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
487 /// assert_eq!(iter.next(), Some(&2));
488 /// assert_eq!(iter.next(), None);
494 /// let a = [0, 1, 2];
496 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
498 /// assert_eq!(iter.next(), Some(&2));
499 /// assert_eq!(iter.next(), None);
504 #[stable(feature = "rust1", since = "1.0.0")]
505 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
506 Self: Sized, P: FnMut(&Self::Item) -> bool,
508 Filter{iter: self, predicate: predicate}
511 /// Creates an iterator that both filters and maps.
513 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
514 /// iterator which calls this closure on each element. If the closure
515 /// returns `Some(element)`, then that element is returned. If the
516 /// closure returns `None`, it will try again, and call the closure on the
517 /// next element, seeing if it will return `Some`.
519 /// [`Option<T>`]: ../../std/option/enum.Option.html
521 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
524 /// [`filter()`]: #method.filter
525 /// [`map()`]: #method.map
527 /// > If the closure returns `Some(element)`, then that element is returned.
529 /// In other words, it removes the [`Option<T>`] layer automatically. If your
530 /// mapping is already returning an [`Option<T>`] and you want to skip over
531 /// `None`s, then `filter_map()` is much, much nicer to use.
538 /// let a = ["1", "2", "lol"];
540 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
542 /// assert_eq!(iter.next(), Some(1));
543 /// assert_eq!(iter.next(), Some(2));
544 /// assert_eq!(iter.next(), None);
547 /// Here's the same example, but with [`filter()`] and [`map()`]:
550 /// let a = ["1", "2", "lol"];
552 /// let mut iter = a.iter()
553 /// .map(|s| s.parse().ok())
554 /// .filter(|s| s.is_some());
556 /// assert_eq!(iter.next(), Some(Some(1)));
557 /// assert_eq!(iter.next(), Some(Some(2)));
558 /// assert_eq!(iter.next(), None);
561 /// There's an extra layer of `Some` in there.
563 #[stable(feature = "rust1", since = "1.0.0")]
564 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
565 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
567 FilterMap { iter: self, f: f }
570 /// Creates an iterator which gives the current iteration count as well as
573 /// The iterator returned yields pairs `(i, val)`, where `i` is the
574 /// current index of iteration and `val` is the value returned by the
577 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
578 /// different sized integer, the [`zip()`] function provides similar
581 /// [`usize`]: ../../std/primitive.usize.html
582 /// [`zip()`]: #method.zip
584 /// # Overflow Behavior
586 /// The method does no guarding against overflows, so enumerating more than
587 /// [`usize::MAX`] elements either produces the wrong result or panics. If
588 /// debug assertions are enabled, a panic is guaranteed.
590 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
594 /// The returned iterator might panic if the to-be-returned index would
595 /// overflow a `usize`.
600 /// let a = ['a', 'b', 'c'];
602 /// let mut iter = a.iter().enumerate();
604 /// assert_eq!(iter.next(), Some((0, &'a')));
605 /// assert_eq!(iter.next(), Some((1, &'b')));
606 /// assert_eq!(iter.next(), Some((2, &'c')));
607 /// assert_eq!(iter.next(), None);
610 #[stable(feature = "rust1", since = "1.0.0")]
611 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
612 Enumerate { iter: self, count: 0 }
615 /// Creates an iterator which can use `peek` to look at the next element of
616 /// the iterator without consuming it.
618 /// Adds a [`peek()`] method to an iterator. See its documentation for
619 /// more information.
621 /// Note that the underlying iterator is still advanced when `peek` is
622 /// called for the first time: In order to retrieve the next element,
623 /// `next` is called on the underlying iterator, hence any side effects of
624 /// the `next` method will occur.
626 /// [`peek()`]: struct.Peekable.html#method.peek
633 /// let xs = [1, 2, 3];
635 /// let mut iter = xs.iter().peekable();
637 /// // peek() lets us see into the future
638 /// assert_eq!(iter.peek(), Some(&&1));
639 /// assert_eq!(iter.next(), Some(&1));
641 /// assert_eq!(iter.next(), Some(&2));
643 /// // we can peek() multiple times, the iterator won't advance
644 /// assert_eq!(iter.peek(), Some(&&3));
645 /// assert_eq!(iter.peek(), Some(&&3));
647 /// assert_eq!(iter.next(), Some(&3));
649 /// // after the iterator is finished, so is peek()
650 /// assert_eq!(iter.peek(), None);
651 /// assert_eq!(iter.next(), None);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 fn peekable(self) -> Peekable<Self> where Self: Sized {
656 Peekable{iter: self, peeked: None}
659 /// Creates an iterator that [`skip()`]s elements based on a predicate.
661 /// [`skip()`]: #method.skip
663 /// `skip_while()` takes a closure as an argument. It will call this
664 /// closure on each element of the iterator, and ignore elements
665 /// until it returns `false`.
667 /// After `false` is returned, `skip_while()`'s job is over, and the
668 /// rest of the elements are yielded.
675 /// let a = [-1i32, 0, 1];
677 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
679 /// assert_eq!(iter.next(), Some(&0));
680 /// assert_eq!(iter.next(), Some(&1));
681 /// assert_eq!(iter.next(), None);
684 /// Because the closure passed to `skip_while()` takes a reference, and many
685 /// iterators iterate over references, this leads to a possibly confusing
686 /// situation, where the type of the closure is a double reference:
689 /// let a = [-1, 0, 1];
691 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
693 /// assert_eq!(iter.next(), Some(&0));
694 /// assert_eq!(iter.next(), Some(&1));
695 /// assert_eq!(iter.next(), None);
698 /// Stopping after an initial `false`:
701 /// let a = [-1, 0, 1, -2];
703 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
705 /// assert_eq!(iter.next(), Some(&0));
706 /// assert_eq!(iter.next(), Some(&1));
708 /// // while this would have been false, since we already got a false,
709 /// // skip_while() isn't used any more
710 /// assert_eq!(iter.next(), Some(&-2));
712 /// assert_eq!(iter.next(), None);
715 #[stable(feature = "rust1", since = "1.0.0")]
716 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
717 Self: Sized, P: FnMut(&Self::Item) -> bool,
719 SkipWhile{iter: self, flag: false, predicate: predicate}
722 /// Creates an iterator that yields elements based on a predicate.
724 /// `take_while()` takes a closure as an argument. It will call this
725 /// closure on each element of the iterator, and yield elements
726 /// while it returns `true`.
728 /// After `false` is returned, `take_while()`'s job is over, and the
729 /// rest of the elements are ignored.
736 /// let a = [-1i32, 0, 1];
738 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
740 /// assert_eq!(iter.next(), Some(&-1));
741 /// assert_eq!(iter.next(), None);
744 /// Because the closure passed to `take_while()` takes a reference, and many
745 /// iterators iterate over references, this leads to a possibly confusing
746 /// situation, where the type of the closure is a double reference:
749 /// let a = [-1, 0, 1];
751 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
753 /// assert_eq!(iter.next(), Some(&-1));
754 /// assert_eq!(iter.next(), None);
757 /// Stopping after an initial `false`:
760 /// let a = [-1, 0, 1, -2];
762 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
764 /// assert_eq!(iter.next(), Some(&-1));
766 /// // We have more elements that are less than zero, but since we already
767 /// // got a false, take_while() isn't used any more
768 /// assert_eq!(iter.next(), None);
771 /// Because `take_while()` needs to look at the value in order to see if it
772 /// should be included or not, consuming iterators will see that it is
776 /// let a = [1, 2, 3, 4];
777 /// let mut iter = a.into_iter();
779 /// let result: Vec<i32> = iter.by_ref()
780 /// .take_while(|n| **n != 3)
784 /// assert_eq!(result, &[1, 2]);
786 /// let result: Vec<i32> = iter.cloned().collect();
788 /// assert_eq!(result, &[4]);
791 /// The `3` is no longer there, because it was consumed in order to see if
792 /// the iteration should stop, but wasn't placed back into the iterator or
793 /// some similar thing.
795 #[stable(feature = "rust1", since = "1.0.0")]
796 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
797 Self: Sized, P: FnMut(&Self::Item) -> bool,
799 TakeWhile{iter: self, flag: false, predicate: predicate}
802 /// Creates an iterator that skips the first `n` elements.
804 /// After they have been consumed, the rest of the elements are yielded.
811 /// let a = [1, 2, 3];
813 /// let mut iter = a.iter().skip(2);
815 /// assert_eq!(iter.next(), Some(&3));
816 /// assert_eq!(iter.next(), None);
819 #[stable(feature = "rust1", since = "1.0.0")]
820 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
821 Skip{iter: self, n: n}
824 /// Creates an iterator that yields its first `n` elements.
831 /// let a = [1, 2, 3];
833 /// let mut iter = a.iter().take(2);
835 /// assert_eq!(iter.next(), Some(&1));
836 /// assert_eq!(iter.next(), Some(&2));
837 /// assert_eq!(iter.next(), None);
840 /// `take()` is often used with an infinite iterator, to make it finite:
843 /// let mut iter = (0..).take(3);
845 /// assert_eq!(iter.next(), Some(0));
846 /// assert_eq!(iter.next(), Some(1));
847 /// assert_eq!(iter.next(), Some(2));
848 /// assert_eq!(iter.next(), None);
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
853 Take{iter: self, n: n}
856 /// An iterator adaptor similar to [`fold()`] that holds internal state and
857 /// produces a new iterator.
859 /// [`fold()`]: #method.fold
861 /// `scan()` takes two arguments: an initial value which seeds the internal
862 /// state, and a closure with two arguments, the first being a mutable
863 /// reference to the internal state and the second an iterator element.
864 /// The closure can assign to the internal state to share state between
867 /// On iteration, the closure will be applied to each element of the
868 /// iterator and the return value from the closure, an [`Option`], is
869 /// yielded by the iterator.
871 /// [`Option`]: ../../std/option/enum.Option.html
878 /// let a = [1, 2, 3];
880 /// let mut iter = a.iter().scan(1, |state, &x| {
881 /// // each iteration, we'll multiply the state by the element
882 /// *state = *state * x;
884 /// // the value passed on to the next iteration
888 /// assert_eq!(iter.next(), Some(1));
889 /// assert_eq!(iter.next(), Some(2));
890 /// assert_eq!(iter.next(), Some(6));
891 /// assert_eq!(iter.next(), None);
894 #[stable(feature = "rust1", since = "1.0.0")]
895 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
896 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
898 Scan{iter: self, f: f, state: initial_state}
901 /// Creates an iterator that works like map, but flattens nested structure.
903 /// The [`map()`] adapter is very useful, but only when the closure
904 /// argument produces values. If it produces an iterator instead, there's
905 /// an extra layer of indirection. `flat_map()` will remove this extra layer
908 /// [`map()`]: #method.map
910 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
911 /// one item for each element, and `flat_map()`'s closure returns an
912 /// iterator for each element.
919 /// let words = ["alpha", "beta", "gamma"];
921 /// // chars() returns an iterator
922 /// let merged: String = words.iter()
923 /// .flat_map(|s| s.chars())
925 /// assert_eq!(merged, "alphabetagamma");
928 #[stable(feature = "rust1", since = "1.0.0")]
929 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
930 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
932 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
935 /// Creates an iterator which ends after the first `None`.
937 /// After an iterator returns `None`, future calls may or may not yield
938 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
939 /// `None` is given, it will always return `None` forever.
946 /// // an iterator which alternates between Some and None
947 /// struct Alternate {
951 /// impl Iterator for Alternate {
954 /// fn next(&mut self) -> Option<i32> {
955 /// let val = self.state;
956 /// self.state = self.state + 1;
958 /// // if it's even, Some(i32), else None
959 /// if val % 2 == 0 {
967 /// let mut iter = Alternate { state: 0 };
969 /// // we can see our iterator going back and forth
970 /// assert_eq!(iter.next(), Some(0));
971 /// assert_eq!(iter.next(), None);
972 /// assert_eq!(iter.next(), Some(2));
973 /// assert_eq!(iter.next(), None);
975 /// // however, once we fuse it...
976 /// let mut iter = iter.fuse();
978 /// assert_eq!(iter.next(), Some(4));
979 /// assert_eq!(iter.next(), None);
981 /// // it will always return None after the first time.
982 /// assert_eq!(iter.next(), None);
983 /// assert_eq!(iter.next(), None);
984 /// assert_eq!(iter.next(), None);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn fuse(self) -> Fuse<Self> where Self: Sized {
989 Fuse{iter: self, done: false}
992 /// Do something with each element of an iterator, passing the value on.
994 /// When using iterators, you'll often chain several of them together.
995 /// While working on such code, you might want to check out what's
996 /// happening at various parts in the pipeline. To do that, insert
997 /// a call to `inspect()`.
999 /// It's much more common for `inspect()` to be used as a debugging tool
1000 /// than to exist in your final code, but never say never.
1007 /// let a = [1, 4, 2, 3];
1009 /// // this iterator sequence is complex.
1010 /// let sum = a.iter()
1012 /// .filter(|&x| x % 2 == 0)
1013 /// .fold(0, |sum, i| sum + i);
1015 /// println!("{}", sum);
1017 /// // let's add some inspect() calls to investigate what's happening
1018 /// let sum = a.iter()
1020 /// .inspect(|x| println!("about to filter: {}", x))
1021 /// .filter(|&x| x % 2 == 0)
1022 /// .inspect(|x| println!("made it through filter: {}", x))
1023 /// .fold(0, |sum, i| sum + i);
1025 /// println!("{}", sum);
1028 /// This will print:
1031 /// about to filter: 1
1032 /// about to filter: 4
1033 /// made it through filter: 4
1034 /// about to filter: 2
1035 /// made it through filter: 2
1036 /// about to filter: 3
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1042 Self: Sized, F: FnMut(&Self::Item),
1044 Inspect{iter: self, f: f}
1047 /// Borrows an iterator, rather than consuming it.
1049 /// This is useful to allow applying iterator adaptors while still
1050 /// retaining ownership of the original iterator.
1057 /// let a = [1, 2, 3];
1059 /// let iter = a.into_iter();
1061 /// let sum: i32 = iter.take(5)
1062 /// .fold(0, |acc, &i| acc + i );
1064 /// assert_eq!(sum, 6);
1066 /// // if we try to use iter again, it won't work. The following line
1067 /// // gives "error: use of moved value: `iter`
1068 /// // assert_eq!(iter.next(), None);
1070 /// // let's try that again
1071 /// let a = [1, 2, 3];
1073 /// let mut iter = a.into_iter();
1075 /// // instead, we add in a .by_ref()
1076 /// let sum: i32 = iter.by_ref()
1078 /// .fold(0, |acc, &i| acc + i );
1080 /// assert_eq!(sum, 3);
1082 /// // now this is just fine:
1083 /// assert_eq!(iter.next(), Some(&3));
1084 /// assert_eq!(iter.next(), None);
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1089 /// Transforms an iterator into a collection.
1091 /// `collect()` can take anything iterable, and turn it into a relevant
1092 /// collection. This is one of the more powerful methods in the standard
1093 /// library, used in a variety of contexts.
1095 /// The most basic pattern in which `collect()` is used is to turn one
1096 /// collection into another. You take a collection, call `iter()` on it,
1097 /// do a bunch of transformations, and then `collect()` at the end.
1099 /// One of the keys to `collect()`'s power is that many things you might
1100 /// not think of as 'collections' actually are. For example, a [`String`]
1101 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1102 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1105 /// [`String`]: ../../std/string/struct.String.html
1106 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1107 /// [`char`]: ../../std/primitive.char.html
1109 /// Because `collect()` is so general, it can cause problems with type
1110 /// inference. As such, `collect()` is one of the few times you'll see
1111 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1112 /// helps the inference algorithm understand specifically which collection
1113 /// you're trying to collect into.
1120 /// let a = [1, 2, 3];
1122 /// let doubled: Vec<i32> = a.iter()
1123 /// .map(|&x| x * 2)
1126 /// assert_eq!(vec![2, 4, 6], doubled);
1129 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1130 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1132 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1135 /// use std::collections::VecDeque;
1137 /// let a = [1, 2, 3];
1139 /// let doubled: VecDeque<i32> = a.iter()
1140 /// .map(|&x| x * 2)
1143 /// assert_eq!(2, doubled[0]);
1144 /// assert_eq!(4, doubled[1]);
1145 /// assert_eq!(6, doubled[2]);
1148 /// Using the 'turbofish' instead of annotating `doubled`:
1151 /// let a = [1, 2, 3];
1153 /// let doubled = a.iter()
1154 /// .map(|&x| x * 2)
1155 /// .collect::<Vec<i32>>();
1157 /// assert_eq!(vec![2, 4, 6], doubled);
1160 /// Because `collect()` cares about what you're collecting into, you can
1161 /// still use a partial type hint, `_`, with the turbofish:
1164 /// let a = [1, 2, 3];
1166 /// let doubled = a.iter()
1167 /// .map(|&x| x * 2)
1168 /// .collect::<Vec<_>>();
1170 /// assert_eq!(vec![2, 4, 6], doubled);
1173 /// Using `collect()` to make a [`String`]:
1176 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1178 /// let hello: String = chars.iter()
1179 /// .map(|&x| x as u8)
1180 /// .map(|x| (x + 1) as char)
1183 /// assert_eq!("hello", hello);
1186 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1187 /// see if any of them failed:
1190 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1192 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1194 /// // gives us the first error
1195 /// assert_eq!(Err("nope"), result);
1197 /// let results = [Ok(1), Ok(3)];
1199 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1201 /// // gives us the list of answers
1202 /// assert_eq!(Ok(vec![1, 3]), result);
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1207 FromIterator::from_iter(self)
1210 /// Consumes an iterator, creating two collections from it.
1212 /// The predicate passed to `partition()` can return `true`, or `false`.
1213 /// `partition()` returns a pair, all of the elements for which it returned
1214 /// `true`, and all of the elements for which it returned `false`.
1221 /// let a = [1, 2, 3];
1223 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1224 /// .partition(|&n| n % 2 == 0);
1226 /// assert_eq!(even, vec![2]);
1227 /// assert_eq!(odd, vec![1, 3]);
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 fn partition<B, F>(self, mut f: F) -> (B, B) where
1232 B: Default + Extend<Self::Item>,
1233 F: FnMut(&Self::Item) -> bool
1235 let mut left: B = Default::default();
1236 let mut right: B = Default::default();
1240 left.extend(Some(x))
1242 right.extend(Some(x))
1249 /// An iterator adaptor that applies a function, producing a single, final value.
1251 /// `fold()` takes two arguments: an initial value, and a closure with two
1252 /// arguments: an 'accumulator', and an element. The closure returns the value that
1253 /// the accumulator should have for the next iteration.
1255 /// The initial value is the value the accumulator will have on the first
1258 /// After applying this closure to every element of the iterator, `fold()`
1259 /// returns the accumulator.
1261 /// This operation is sometimes called 'reduce' or 'inject'.
1263 /// Folding is useful whenever you have a collection of something, and want
1264 /// to produce a single value from it.
1271 /// let a = [1, 2, 3];
1273 /// // the sum of all of the elements of a
1274 /// let sum = a.iter()
1275 /// .fold(0, |acc, &x| acc + x);
1277 /// assert_eq!(sum, 6);
1280 /// Let's walk through each step of the iteration here:
1282 /// | element | acc | x | result |
1283 /// |---------|-----|---|--------|
1285 /// | 1 | 0 | 1 | 1 |
1286 /// | 2 | 1 | 2 | 3 |
1287 /// | 3 | 3 | 3 | 6 |
1289 /// And so, our final result, `6`.
1291 /// It's common for people who haven't used iterators a lot to
1292 /// use a `for` loop with a list of things to build up a result. Those
1293 /// can be turned into `fold()`s:
1296 /// let numbers = [1, 2, 3, 4, 5];
1298 /// let mut result = 0;
1301 /// for i in &numbers {
1302 /// result = result + i;
1306 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1308 /// // they're the same
1309 /// assert_eq!(result, result2);
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 fn fold<B, F>(self, init: B, mut f: F) -> B where
1314 Self: Sized, F: FnMut(B, Self::Item) -> B,
1316 let mut accum = init;
1318 accum = f(accum, x);
1323 /// Tests if every element of the iterator matches a predicate.
1325 /// `all()` takes a closure that returns `true` or `false`. It applies
1326 /// this closure to each element of the iterator, and if they all return
1327 /// `true`, then so does `all()`. If any of them return `false`, it
1328 /// returns `false`.
1330 /// `all()` is short-circuiting; in other words, it will stop processing
1331 /// as soon as it finds a `false`, given that no matter what else happens,
1332 /// the result will also be `false`.
1334 /// An empty iterator returns `true`.
1341 /// let a = [1, 2, 3];
1343 /// assert!(a.iter().all(|&x| x > 0));
1345 /// assert!(!a.iter().all(|&x| x > 2));
1348 /// Stopping at the first `false`:
1351 /// let a = [1, 2, 3];
1353 /// let mut iter = a.iter();
1355 /// assert!(!iter.all(|&x| x != 2));
1357 /// // we can still use `iter`, as there are more elements.
1358 /// assert_eq!(iter.next(), Some(&3));
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 fn all<F>(&mut self, mut f: F) -> bool where
1363 Self: Sized, F: FnMut(Self::Item) -> bool
1373 /// Tests if any element of the iterator matches a predicate.
1375 /// `any()` takes a closure that returns `true` or `false`. It applies
1376 /// this closure to each element of the iterator, and if any of them return
1377 /// `true`, then so does `any()`. If they all return `false`, it
1378 /// returns `false`.
1380 /// `any()` is short-circuiting; in other words, it will stop processing
1381 /// as soon as it finds a `true`, given that no matter what else happens,
1382 /// the result will also be `true`.
1384 /// An empty iterator returns `false`.
1391 /// let a = [1, 2, 3];
1393 /// assert!(a.iter().any(|&x| x > 0));
1395 /// assert!(!a.iter().any(|&x| x > 5));
1398 /// Stopping at the first `true`:
1401 /// let a = [1, 2, 3];
1403 /// let mut iter = a.iter();
1405 /// assert!(iter.any(|&x| x != 2));
1407 /// // we can still use `iter`, as there are more elements.
1408 /// assert_eq!(iter.next(), Some(&2));
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 fn any<F>(&mut self, mut f: F) -> bool where
1414 F: FnMut(Self::Item) -> bool
1424 /// Searches for an element of an iterator that satisfies a predicate.
1426 /// `find()` takes a closure that returns `true` or `false`. It applies
1427 /// this closure to each element of the iterator, and if any of them return
1428 /// `true`, then `find()` returns `Some(element)`. If they all return
1429 /// `false`, it returns `None`.
1431 /// `find()` is short-circuiting; in other words, it will stop processing
1432 /// as soon as the closure returns `true`.
1434 /// Because `find()` takes a reference, and many iterators iterate over
1435 /// references, this leads to a possibly confusing situation where the
1436 /// argument is a double reference. You can see this effect in the
1437 /// examples below, with `&&x`.
1444 /// let a = [1, 2, 3];
1446 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1448 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1451 /// Stopping at the first `true`:
1454 /// let a = [1, 2, 3];
1456 /// let mut iter = a.iter();
1458 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1460 /// // we can still use `iter`, as there are more elements.
1461 /// assert_eq!(iter.next(), Some(&3));
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1467 P: FnMut(&Self::Item) -> bool,
1470 if predicate(&x) { return Some(x) }
1475 /// Searches for an element in an iterator, returning its index.
1477 /// `position()` takes a closure that returns `true` or `false`. It applies
1478 /// this closure to each element of the iterator, and if one of them
1479 /// returns `true`, then `position()` returns `Some(index)`. If all of
1480 /// them return `false`, it returns `None`.
1482 /// `position()` is short-circuiting; in other words, it will stop
1483 /// processing as soon as it finds a `true`.
1485 /// # Overflow Behavior
1487 /// The method does no guarding against overflows, so if there are more
1488 /// than `usize::MAX` non-matching elements, it either produces the wrong
1489 /// result or panics. If debug assertions are enabled, a panic is
1494 /// This function might panic if the iterator has more than `usize::MAX`
1495 /// non-matching elements.
1502 /// let a = [1, 2, 3];
1504 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1506 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1509 /// Stopping at the first `true`:
1512 /// let a = [1, 2, 3];
1514 /// let mut iter = a.iter();
1516 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1518 /// // we can still use `iter`, as there are more elements.
1519 /// assert_eq!(iter.next(), Some(&3));
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1525 P: FnMut(Self::Item) -> bool,
1527 // `enumerate` might overflow.
1528 for (i, x) in self.enumerate() {
1536 /// Searches for an element in an iterator from the right, returning its
1539 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1540 /// this closure to each element of the iterator, starting from the end,
1541 /// and if one of them returns `true`, then `rposition()` returns
1542 /// `Some(index)`. If all of them return `false`, it returns `None`.
1544 /// `rposition()` is short-circuiting; in other words, it will stop
1545 /// processing as soon as it finds a `true`.
1552 /// let a = [1, 2, 3];
1554 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1556 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1559 /// Stopping at the first `true`:
1562 /// let a = [1, 2, 3];
1564 /// let mut iter = a.iter();
1566 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1568 /// // we can still use `iter`, as there are more elements.
1569 /// assert_eq!(iter.next(), Some(&1));
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1574 P: FnMut(Self::Item) -> bool,
1575 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1577 let mut i = self.len();
1579 while let Some(v) = self.next_back() {
1583 // No need for an overflow check here, because `ExactSizeIterator`
1584 // implies that the number of elements fits into a `usize`.
1590 /// Returns the maximum element of an iterator.
1592 /// If the two elements are equally maximum, the latest element is
1600 /// let a = [1, 2, 3];
1602 /// assert_eq!(a.iter().max(), Some(&3));
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1610 // switch to y even if it is only equal, to preserve
1612 |_, x, _, y| *x <= *y)
1616 /// Returns the minimum element of an iterator.
1618 /// If the two elements are equally minimum, the first element is
1626 /// let a = [1, 2, 3];
1628 /// assert_eq!(a.iter().min(), Some(&1));
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1636 // only switch to y if it is strictly smaller, to
1637 // preserve stability.
1638 |_, x, _, y| *x > *y)
1642 /// Returns the element that gives the maximum value from the
1643 /// specified function.
1645 /// Returns the rightmost element if the comparison determines two elements
1646 /// to be equally maximum.
1651 /// let a = [-3_i32, 0, 1, 5, -10];
1652 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1655 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1656 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1657 where Self: Sized, F: FnMut(&Self::Item) -> B,
1661 // switch to y even if it is only equal, to preserve
1663 |x_p, _, y_p, _| x_p <= y_p)
1667 /// Returns the element that gives the maximum value with respect to the
1668 /// specified comparison function.
1670 /// Returns the rightmost element if the comparison determines two elements
1671 /// to be equally maximum.
1676 /// let a = [-3_i32, 0, 1, 5, -10];
1677 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1680 #[unstable(feature = "iter_max_by", issue="1722")]
1681 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1682 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1686 // switch to y even if it is only equal, to preserve
1688 |_, x, _, y| Ordering::Greater != compare(x, y))
1692 /// Returns the element that gives the minimum value from the
1693 /// specified function.
1695 /// Returns the latest element if the comparison determines two elements
1696 /// to be equally minimum.
1701 /// let a = [-3_i32, 0, 1, 5, -10];
1702 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1704 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1705 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1706 where Self: Sized, F: FnMut(&Self::Item) -> B,
1710 // only switch to y if it is strictly smaller, to
1711 // preserve stability.
1712 |x_p, _, y_p, _| x_p > y_p)
1716 /// Returns the element that gives the minimum value with respect to the
1717 /// specified comparison function.
1719 /// Returns the latest element if the comparison determines two elements
1720 /// to be equally minimum.
1725 /// let a = [-3_i32, 0, 1, 5, -10];
1726 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1729 #[unstable(feature = "iter_min_by", issue="1722")]
1730 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
1731 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1735 // switch to y even if it is strictly smaller, to
1736 // preserve stability.
1737 |_, x, _, y| Ordering::Greater == compare(x, y))
1742 /// Reverses an iterator's direction.
1744 /// Usually, iterators iterate from left to right. After using `rev()`,
1745 /// an iterator will instead iterate from right to left.
1747 /// This is only possible if the iterator has an end, so `rev()` only
1748 /// works on [`DoubleEndedIterator`]s.
1750 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1755 /// let a = [1, 2, 3];
1757 /// let mut iter = a.iter().rev();
1759 /// assert_eq!(iter.next(), Some(&3));
1760 /// assert_eq!(iter.next(), Some(&2));
1761 /// assert_eq!(iter.next(), Some(&1));
1763 /// assert_eq!(iter.next(), None);
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1771 /// Converts an iterator of pairs into a pair of containers.
1773 /// `unzip()` consumes an entire iterator of pairs, producing two
1774 /// collections: one from the left elements of the pairs, and one
1775 /// from the right elements.
1777 /// This function is, in some sense, the opposite of [`zip()`].
1779 /// [`zip()`]: #method.zip
1786 /// let a = [(1, 2), (3, 4)];
1788 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1790 /// assert_eq!(left, [1, 3]);
1791 /// assert_eq!(right, [2, 4]);
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1795 FromA: Default + Extend<A>,
1796 FromB: Default + Extend<B>,
1797 Self: Sized + Iterator<Item=(A, B)>,
1799 let mut ts: FromA = Default::default();
1800 let mut us: FromB = Default::default();
1802 for (t, u) in self {
1810 /// Creates an iterator which `clone()`s all of its elements.
1812 /// This is useful when you have an iterator over `&T`, but you need an
1813 /// iterator over `T`.
1820 /// let a = [1, 2, 3];
1822 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1824 /// // cloned is the same as .map(|&x| x), for integers
1825 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1827 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1828 /// assert_eq!(v_map, vec![1, 2, 3]);
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1832 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1837 /// Repeats an iterator endlessly.
1839 /// Instead of stopping at `None`, the iterator will instead start again,
1840 /// from the beginning. After iterating again, it will start at the
1841 /// beginning again. And again. And again. Forever.
1848 /// let a = [1, 2, 3];
1850 /// let mut it = a.iter().cycle();
1852 /// assert_eq!(it.next(), Some(&1));
1853 /// assert_eq!(it.next(), Some(&2));
1854 /// assert_eq!(it.next(), Some(&3));
1855 /// assert_eq!(it.next(), Some(&1));
1856 /// assert_eq!(it.next(), Some(&2));
1857 /// assert_eq!(it.next(), Some(&3));
1858 /// assert_eq!(it.next(), Some(&1));
1860 #[stable(feature = "rust1", since = "1.0.0")]
1862 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1863 Cycle{orig: self.clone(), iter: self}
1866 /// Sums the elements of an iterator.
1868 /// Takes each element, adds them together, and returns the result.
1870 /// An empty iterator returns the zero value of the type.
1874 /// When calling `sum` and a primitive integer type is being returned, this
1875 /// method will panic if the computation overflows.
1882 /// let a = [1, 2, 3];
1883 /// let sum: i32 = a.iter().sum();
1885 /// assert_eq!(sum, 6);
1887 #[stable(feature = "iter_arith", since = "1.11.0")]
1888 fn sum<S>(self) -> S
1895 /// Iterates over the entire iterator, multiplying all the elements
1897 /// An empty iterator returns the one value of the type.
1901 /// When calling `product` and a primitive integer type is being returned,
1902 /// this method will panic if the computation overflows.
1907 /// fn factorial(n: u32) -> u32 {
1908 /// (1..).take_while(|&i| i <= n).product()
1910 /// assert_eq!(factorial(0), 1);
1911 /// assert_eq!(factorial(1), 1);
1912 /// assert_eq!(factorial(5), 120);
1914 #[stable(feature = "iter_arith", since = "1.11.0")]
1915 fn product<P>(self) -> P
1917 P: Product<Self::Item>,
1919 Product::product(self)
1922 /// Lexicographically compares the elements of this `Iterator` with those
1924 #[stable(feature = "iter_order", since = "1.5.0")]
1925 fn cmp<I>(mut self, other: I) -> Ordering where
1926 I: IntoIterator<Item = Self::Item>,
1930 let mut other = other.into_iter();
1933 match (self.next(), other.next()) {
1934 (None, None) => return Ordering::Equal,
1935 (None, _ ) => return Ordering::Less,
1936 (_ , None) => return Ordering::Greater,
1937 (Some(x), Some(y)) => match x.cmp(&y) {
1938 Ordering::Equal => (),
1939 non_eq => return non_eq,
1945 /// Lexicographically compares the elements of this `Iterator` with those
1947 #[stable(feature = "iter_order", since = "1.5.0")]
1948 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1950 Self::Item: PartialOrd<I::Item>,
1953 let mut other = other.into_iter();
1956 match (self.next(), other.next()) {
1957 (None, None) => return Some(Ordering::Equal),
1958 (None, _ ) => return Some(Ordering::Less),
1959 (_ , None) => return Some(Ordering::Greater),
1960 (Some(x), Some(y)) => match x.partial_cmp(&y) {
1961 Some(Ordering::Equal) => (),
1962 non_eq => return non_eq,
1968 /// Determines if the elements of this `Iterator` are equal to those of
1970 #[stable(feature = "iter_order", since = "1.5.0")]
1971 fn eq<I>(mut self, other: I) -> bool where
1973 Self::Item: PartialEq<I::Item>,
1976 let mut other = other.into_iter();
1979 match (self.next(), other.next()) {
1980 (None, None) => return true,
1981 (None, _) | (_, None) => return false,
1982 (Some(x), Some(y)) => if x != y { return false },
1987 /// Determines if the elements of this `Iterator` are unequal to those of
1989 #[stable(feature = "iter_order", since = "1.5.0")]
1990 fn ne<I>(mut self, other: I) -> bool where
1992 Self::Item: PartialEq<I::Item>,
1995 let mut other = other.into_iter();
1998 match (self.next(), other.next()) {
1999 (None, None) => return false,
2000 (None, _) | (_, None) => return true,
2001 (Some(x), Some(y)) => if x.ne(&y) { return true },
2006 /// Determines if the elements of this `Iterator` are lexicographically
2007 /// less than those of another.
2008 #[stable(feature = "iter_order", since = "1.5.0")]
2009 fn lt<I>(mut self, other: I) -> bool where
2011 Self::Item: PartialOrd<I::Item>,
2014 let mut other = other.into_iter();
2017 match (self.next(), other.next()) {
2018 (None, None) => return false,
2019 (None, _ ) => return true,
2020 (_ , None) => return false,
2021 (Some(x), Some(y)) => {
2022 match x.partial_cmp(&y) {
2023 Some(Ordering::Less) => return true,
2024 Some(Ordering::Equal) => {}
2025 Some(Ordering::Greater) => return false,
2026 None => return false,
2033 /// Determines if the elements of this `Iterator` are lexicographically
2034 /// less or equal to those of another.
2035 #[stable(feature = "iter_order", since = "1.5.0")]
2036 fn le<I>(mut self, other: I) -> bool where
2038 Self::Item: PartialOrd<I::Item>,
2041 let mut other = other.into_iter();
2044 match (self.next(), other.next()) {
2045 (None, None) => return true,
2046 (None, _ ) => return true,
2047 (_ , None) => return false,
2048 (Some(x), Some(y)) => {
2049 match x.partial_cmp(&y) {
2050 Some(Ordering::Less) => return true,
2051 Some(Ordering::Equal) => {}
2052 Some(Ordering::Greater) => return false,
2053 None => return false,
2060 /// Determines if the elements of this `Iterator` are lexicographically
2061 /// greater than those of another.
2062 #[stable(feature = "iter_order", since = "1.5.0")]
2063 fn gt<I>(mut self, other: I) -> bool where
2065 Self::Item: PartialOrd<I::Item>,
2068 let mut other = other.into_iter();
2071 match (self.next(), other.next()) {
2072 (None, None) => return false,
2073 (None, _ ) => return false,
2074 (_ , None) => return true,
2075 (Some(x), Some(y)) => {
2076 match x.partial_cmp(&y) {
2077 Some(Ordering::Less) => return false,
2078 Some(Ordering::Equal) => {}
2079 Some(Ordering::Greater) => return true,
2080 None => return false,
2087 /// Determines if the elements of this `Iterator` are lexicographically
2088 /// greater than or equal to those of another.
2089 #[stable(feature = "iter_order", since = "1.5.0")]
2090 fn ge<I>(mut self, other: I) -> bool where
2092 Self::Item: PartialOrd<I::Item>,
2095 let mut other = other.into_iter();
2098 match (self.next(), other.next()) {
2099 (None, None) => return true,
2100 (None, _ ) => return false,
2101 (_ , None) => return true,
2102 (Some(x), Some(y)) => {
2103 match x.partial_cmp(&y) {
2104 Some(Ordering::Less) => return false,
2105 Some(Ordering::Equal) => {}
2106 Some(Ordering::Greater) => return true,
2107 None => return false,
2115 /// Select an element from an iterator based on the given projection
2116 /// and "comparison" function.
2118 /// This is an idiosyncratic helper to try to factor out the
2119 /// commonalities of {max,min}{,_by}. In particular, this avoids
2120 /// having to implement optimizations several times.
2122 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2124 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2126 FProj: FnMut(&I::Item) -> B,
2127 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2129 // start with the first element as our selection. This avoids
2130 // having to use `Option`s inside the loop, translating to a
2131 // sizeable performance gain (6x in one case).
2132 it.next().map(|mut sel| {
2133 let mut sel_p = f_proj(&sel);
2136 let x_p = f_proj(&x);
2137 if f_cmp(&sel_p, &sel, &x_p, &x) {
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2148 type Item = I::Item;
2149 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2150 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }