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 ops::{Add, FnMut, Mul};
16 use option::Option::{self, Some, None};
19 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse,
20 Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev,
22 use super::ChainState;
23 use super::{DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator,
27 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
29 /// An interface for dealing with iterators.
31 /// This is the main iterator trait. For more about the concept of iterators
32 /// generally, please see the [module-level documentation]. In particular, you
33 /// may want to know how to [implement `Iterator`][impl].
35 /// [module-level documentation]: index.html
36 /// [impl]: index.html#implementing-iterator
37 #[stable(feature = "rust1", since = "1.0.0")]
38 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
39 `.iter()` or a similar method"]
41 /// The type of the elements being iterated over.
42 #[stable(feature = "rust1", since = "1.0.0")]
45 /// Advances the iterator and returns the next value.
47 /// Returns `None` when iteration is finished. Individual iterator
48 /// implementations may choose to resume iteration, and so calling `next()`
49 /// again may or may not eventually start returning `Some(Item)` again at some
57 /// let a = [1, 2, 3];
59 /// let mut iter = a.iter();
61 /// // A call to next() returns the next value...
62 /// assert_eq!(Some(&1), iter.next());
63 /// assert_eq!(Some(&2), iter.next());
64 /// assert_eq!(Some(&3), iter.next());
66 /// // ... and then None once it's over.
67 /// assert_eq!(None, iter.next());
69 /// // More calls may or may not return None. Here, they always will.
70 /// assert_eq!(None, iter.next());
71 /// assert_eq!(None, iter.next());
73 #[stable(feature = "rust1", since = "1.0.0")]
74 fn next(&mut self) -> Option<Self::Item>;
76 /// Returns the bounds on the remaining length of the iterator.
78 /// Specifically, `size_hint()` returns a tuple where the first element
79 /// is the lower bound, and the second element is the upper bound.
81 /// The second half of the tuple that is returned is an `Option<usize>`. A
82 /// `None` here means that either there is no known upper bound, or the
83 /// upper bound is larger than `usize`.
85 /// # Implementation notes
87 /// It is not enforced that an iterator implementation yields the declared
88 /// number of elements. A buggy iterator may yield less than the lower bound
89 /// or more than the upper bound of elements.
91 /// `size_hint()` is primarily intended to be used for optimizations such as
92 /// reserving space for the elements of the iterator, but must not be
93 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
94 /// implementation of `size_hint()` should not lead to memory safety
97 /// That said, the implementation should provide a correct estimation,
98 /// because otherwise it would be a violation of the trait's protocol.
100 /// The default implementation returns `(0, None)` which is correct for any
108 /// let a = [1, 2, 3];
109 /// let iter = a.iter();
111 /// assert_eq!((3, Some(3)), iter.size_hint());
114 /// A more complex example:
117 /// // The even numbers from zero to ten.
118 /// let iter = (0..10).filter(|x| x % 2 == 0);
120 /// // We might iterate from zero to ten times. Knowing that it's five
121 /// // exactly wouldn't be possible without executing filter().
122 /// assert_eq!((0, Some(10)), iter.size_hint());
124 /// // Let's add one five more numbers with chain()
125 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
127 /// // now both bounds are increased by five
128 /// assert_eq!((5, Some(15)), iter.size_hint());
131 /// Returning `None` for an upper bound:
134 /// // an infinite iterator has no upper bound
137 /// assert_eq!((0, None), iter.size_hint());
140 #[stable(feature = "rust1", since = "1.0.0")]
141 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
143 /// Consumes the iterator, counting the number of iterations and returning it.
145 /// This method will evaluate the iterator until its [`next()`] returns
146 /// `None`. Once `None` is encountered, `count()` returns the number of
147 /// times it called [`next()`].
149 /// [`next()`]: #tymethod.next
151 /// # Overflow Behavior
153 /// The method does no guarding against overflows, so counting elements of
154 /// an iterator with more than `usize::MAX` elements either produces the
155 /// wrong result or panics. If debug assertions are enabled, a panic is
160 /// This function might panic if the iterator has more than `usize::MAX`
168 /// let a = [1, 2, 3];
169 /// assert_eq!(a.iter().count(), 3);
171 /// let a = [1, 2, 3, 4, 5];
172 /// assert_eq!(a.iter().count(), 5);
175 #[rustc_inherit_overflow_checks]
176 #[stable(feature = "rust1", since = "1.0.0")]
177 fn count(self) -> usize where Self: Sized {
179 self.fold(0, |cnt, _| cnt + 1)
182 /// Consumes the iterator, returning the last element.
184 /// This method will evaluate the iterator until it returns `None`. While
185 /// doing so, it keeps track of the current element. After `None` is
186 /// returned, `last()` will then return the last element it saw.
193 /// let a = [1, 2, 3];
194 /// assert_eq!(a.iter().last(), Some(&3));
196 /// let a = [1, 2, 3, 4, 5];
197 /// assert_eq!(a.iter().last(), Some(&5));
200 #[stable(feature = "rust1", since = "1.0.0")]
201 fn last(self) -> Option<Self::Item> where Self: Sized {
203 for x in self { last = Some(x); }
207 /// Consumes the `n` first elements of the iterator, then returns the
210 /// This method will evaluate the iterator `n` times, discarding those elements.
211 /// After it does so, it will call [`next()`] and return its value.
213 /// [`next()`]: #tymethod.next
215 /// Like most indexing operations, the count starts from zero, so `nth(0)`
216 /// returns the first value, `nth(1)` the second, and so on.
218 /// `nth()` will return `None` if `n` is greater than or equal to the length of the
226 /// let a = [1, 2, 3];
227 /// assert_eq!(a.iter().nth(1), Some(&2));
230 /// Calling `nth()` multiple times doesn't rewind the iterator:
233 /// let a = [1, 2, 3];
235 /// let mut iter = a.iter();
237 /// assert_eq!(iter.nth(1), Some(&2));
238 /// assert_eq!(iter.nth(1), None);
241 /// Returning `None` if there are less than `n + 1` elements:
244 /// let a = [1, 2, 3];
245 /// assert_eq!(a.iter().nth(10), None);
248 #[stable(feature = "rust1", since = "1.0.0")]
249 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
251 if n == 0 { return Some(x) }
257 /// Takes two iterators and creates a new iterator over both in sequence.
259 /// `chain()` will return a new iterator which will first iterate over
260 /// values from the first iterator and then over values from the second
263 /// In other words, it links two iterators together, in a chain. 🔗
270 /// let a1 = [1, 2, 3];
271 /// let a2 = [4, 5, 6];
273 /// let mut iter = a1.iter().chain(a2.iter());
275 /// assert_eq!(iter.next(), Some(&1));
276 /// assert_eq!(iter.next(), Some(&2));
277 /// assert_eq!(iter.next(), Some(&3));
278 /// assert_eq!(iter.next(), Some(&4));
279 /// assert_eq!(iter.next(), Some(&5));
280 /// assert_eq!(iter.next(), Some(&6));
281 /// assert_eq!(iter.next(), None);
284 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
285 /// anything that can be converted into an [`Iterator`], not just an
286 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
287 /// [`IntoIterator`], and so can be passed to `chain()` directly:
289 /// [`IntoIterator`]: trait.IntoIterator.html
290 /// [`Iterator`]: trait.Iterator.html
293 /// let s1 = &[1, 2, 3];
294 /// let s2 = &[4, 5, 6];
296 /// let mut iter = s1.iter().chain(s2);
298 /// assert_eq!(iter.next(), Some(&1));
299 /// assert_eq!(iter.next(), Some(&2));
300 /// assert_eq!(iter.next(), Some(&3));
301 /// assert_eq!(iter.next(), Some(&4));
302 /// assert_eq!(iter.next(), Some(&5));
303 /// assert_eq!(iter.next(), Some(&6));
304 /// assert_eq!(iter.next(), None);
307 #[stable(feature = "rust1", since = "1.0.0")]
308 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
309 Self: Sized, U: IntoIterator<Item=Self::Item>,
311 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
314 /// 'Zips up' two iterators into a single iterator of pairs.
316 /// `zip()` returns a new iterator that will iterate over two other
317 /// iterators, returning a tuple where the first element comes from the
318 /// first iterator, and the second element comes from the second iterator.
320 /// In other words, it zips two iterators together, into a single one.
322 /// When either iterator returns `None`, all further calls to `next()`
323 /// will return `None`.
330 /// let a1 = [1, 2, 3];
331 /// let a2 = [4, 5, 6];
333 /// let mut iter = a1.iter().zip(a2.iter());
335 /// assert_eq!(iter.next(), Some((&1, &4)));
336 /// assert_eq!(iter.next(), Some((&2, &5)));
337 /// assert_eq!(iter.next(), Some((&3, &6)));
338 /// assert_eq!(iter.next(), None);
341 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
342 /// anything that can be converted into an [`Iterator`], not just an
343 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
344 /// [`IntoIterator`], and so can be passed to `zip()` directly:
346 /// [`IntoIterator`]: trait.IntoIterator.html
347 /// [`Iterator`]: trait.Iterator.html
350 /// let s1 = &[1, 2, 3];
351 /// let s2 = &[4, 5, 6];
353 /// let mut iter = s1.iter().zip(s2);
355 /// assert_eq!(iter.next(), Some((&1, &4)));
356 /// assert_eq!(iter.next(), Some((&2, &5)));
357 /// assert_eq!(iter.next(), Some((&3, &6)));
358 /// assert_eq!(iter.next(), None);
361 /// `zip()` is often used to zip an infinite iterator to a finite one.
362 /// This works because the finite iterator will eventually return `None`,
363 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
366 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
368 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
370 /// assert_eq!((0, 'f'), enumerate[0]);
371 /// assert_eq!((0, 'f'), zipper[0]);
373 /// assert_eq!((1, 'o'), enumerate[1]);
374 /// assert_eq!((1, 'o'), zipper[1]);
376 /// assert_eq!((2, 'o'), enumerate[2]);
377 /// assert_eq!((2, 'o'), zipper[2]);
380 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
382 #[stable(feature = "rust1", since = "1.0.0")]
383 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
384 Self: Sized, U: IntoIterator
386 Zip::new(self, other.into_iter())
389 /// Takes a closure and creates an iterator which calls that closure on each
392 /// `map()` transforms one iterator into another, by means of its argument:
393 /// something that implements `FnMut`. It produces a new iterator which
394 /// calls this closure on each element of the original iterator.
396 /// If you are good at thinking in types, you can think of `map()` like this:
397 /// If you have an iterator that gives you elements of some type `A`, and
398 /// you want an iterator of some other type `B`, you can use `map()`,
399 /// passing a closure that takes an `A` and returns a `B`.
401 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
402 /// lazy, it is best used when you're already working with other iterators.
403 /// If you're doing some sort of looping for a side effect, it's considered
404 /// more idiomatic to use [`for`] than `map()`.
406 /// [`for`]: ../../book/loops.html#for
413 /// let a = [1, 2, 3];
415 /// let mut iter = a.into_iter().map(|x| 2 * x);
417 /// assert_eq!(iter.next(), Some(2));
418 /// assert_eq!(iter.next(), Some(4));
419 /// assert_eq!(iter.next(), Some(6));
420 /// assert_eq!(iter.next(), None);
423 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
426 /// # #![allow(unused_must_use)]
427 /// // don't do this:
428 /// (0..5).map(|x| println!("{}", x));
430 /// // it won't even execute, as it is lazy. Rust will warn you about this.
432 /// // Instead, use for:
434 /// println!("{}", x);
438 #[stable(feature = "rust1", since = "1.0.0")]
439 fn map<B, F>(self, f: F) -> Map<Self, F> where
440 Self: Sized, F: FnMut(Self::Item) -> B,
442 Map{iter: self, f: f}
445 /// Creates an iterator which uses a closure to determine if an element
446 /// should be yielded.
448 /// The closure must return `true` or `false`. `filter()` creates an
449 /// iterator which calls this closure on each element. If the closure
450 /// returns `true`, then the element is returned. If the closure returns
451 /// `false`, it will try again, and call the closure on the next element,
452 /// seeing if it passes the test.
459 /// let a = [0i32, 1, 2];
461 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
463 /// assert_eq!(iter.next(), Some(&1));
464 /// assert_eq!(iter.next(), Some(&2));
465 /// assert_eq!(iter.next(), None);
468 /// Because the closure passed to `filter()` takes a reference, and many
469 /// iterators iterate over references, this leads to a possibly confusing
470 /// situation, where the type of the closure is a double reference:
473 /// let a = [0, 1, 2];
475 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
477 /// assert_eq!(iter.next(), Some(&2));
478 /// assert_eq!(iter.next(), None);
481 /// It's common to instead use destructuring on the argument to strip away
485 /// let a = [0, 1, 2];
487 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
489 /// assert_eq!(iter.next(), Some(&2));
490 /// assert_eq!(iter.next(), None);
496 /// let a = [0, 1, 2];
498 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
500 /// assert_eq!(iter.next(), Some(&2));
501 /// assert_eq!(iter.next(), None);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
508 Self: Sized, P: FnMut(&Self::Item) -> bool,
510 Filter{iter: self, predicate: predicate}
513 /// Creates an iterator that both filters and maps.
515 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
516 /// iterator which calls this closure on each element. If the closure
517 /// returns `Some(element)`, then that element is returned. If the
518 /// closure returns `None`, it will try again, and call the closure on the
519 /// next element, seeing if it will return `Some`.
521 /// [`Option<T>`]: ../../std/option/enum.Option.html
523 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
526 /// [`filter()`]: #method.filter
527 /// [`map()`]: #method.map
529 /// > If the closure returns `Some(element)`, then that element is returned.
531 /// In other words, it removes the [`Option<T>`] layer automatically. If your
532 /// mapping is already returning an [`Option<T>`] and you want to skip over
533 /// `None`s, then `filter_map()` is much, much nicer to use.
540 /// let a = ["1", "2", "lol"];
542 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
544 /// assert_eq!(iter.next(), Some(1));
545 /// assert_eq!(iter.next(), Some(2));
546 /// assert_eq!(iter.next(), None);
549 /// Here's the same example, but with [`filter()`] and [`map()`]:
552 /// let a = ["1", "2", "lol"];
554 /// let mut iter = a.iter()
555 /// .map(|s| s.parse().ok())
556 /// .filter(|s| s.is_some());
558 /// assert_eq!(iter.next(), Some(Some(1)));
559 /// assert_eq!(iter.next(), Some(Some(2)));
560 /// assert_eq!(iter.next(), None);
563 /// There's an extra layer of `Some` in there.
565 #[stable(feature = "rust1", since = "1.0.0")]
566 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
567 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
569 FilterMap { iter: self, f: f }
572 /// Creates an iterator which gives the current iteration count as well as
575 /// The iterator returned yields pairs `(i, val)`, where `i` is the
576 /// current index of iteration and `val` is the value returned by the
579 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
580 /// different sized integer, the [`zip()`] function provides similar
583 /// [`usize`]: ../../std/primitive.usize.html
584 /// [`zip()`]: #method.zip
586 /// # Overflow Behavior
588 /// The method does no guarding against overflows, so enumerating more than
589 /// [`usize::MAX`] elements either produces the wrong result or panics. If
590 /// debug assertions are enabled, a panic is guaranteed.
592 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
596 /// The returned iterator might panic if the to-be-returned index would
597 /// overflow a `usize`.
602 /// let a = ['a', 'b', 'c'];
604 /// let mut iter = a.iter().enumerate();
606 /// assert_eq!(iter.next(), Some((0, &'a')));
607 /// assert_eq!(iter.next(), Some((1, &'b')));
608 /// assert_eq!(iter.next(), Some((2, &'c')));
609 /// assert_eq!(iter.next(), None);
612 #[stable(feature = "rust1", since = "1.0.0")]
613 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
614 Enumerate { iter: self, count: 0 }
617 /// Creates an iterator which can use `peek` to look at the next element of
618 /// the iterator without consuming it.
620 /// Adds a [`peek()`] method to an iterator. See its documentation for
621 /// more information.
623 /// Note that the underlying iterator is still advanced when `peek` is
624 /// called for the first time: In order to retrieve the next element,
625 /// `next` is called on the underlying iterator, hence any side effects of
626 /// the `next` method will occur.
628 /// [`peek()`]: struct.Peekable.html#method.peek
635 /// let xs = [1, 2, 3];
637 /// let mut iter = xs.iter().peekable();
639 /// // peek() lets us see into the future
640 /// assert_eq!(iter.peek(), Some(&&1));
641 /// assert_eq!(iter.next(), Some(&1));
643 /// assert_eq!(iter.next(), Some(&2));
645 /// // we can peek() multiple times, the iterator won't advance
646 /// assert_eq!(iter.peek(), Some(&&3));
647 /// assert_eq!(iter.peek(), Some(&&3));
649 /// assert_eq!(iter.next(), Some(&3));
651 /// // after the iterator is finished, so is peek()
652 /// assert_eq!(iter.peek(), None);
653 /// assert_eq!(iter.next(), None);
656 #[stable(feature = "rust1", since = "1.0.0")]
657 fn peekable(self) -> Peekable<Self> where Self: Sized {
658 Peekable{iter: self, peeked: None}
661 /// Creates an iterator that [`skip()`]s elements based on a predicate.
663 /// [`skip()`]: #method.skip
665 /// `skip_while()` takes a closure as an argument. It will call this
666 /// closure on each element of the iterator, and ignore elements
667 /// until it returns `false`.
669 /// After `false` is returned, `skip_while()`'s job is over, and the
670 /// rest of the elements are yielded.
677 /// let a = [-1i32, 0, 1];
679 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
681 /// assert_eq!(iter.next(), Some(&0));
682 /// assert_eq!(iter.next(), Some(&1));
683 /// assert_eq!(iter.next(), None);
686 /// Because the closure passed to `skip_while()` takes a reference, and many
687 /// iterators iterate over references, this leads to a possibly confusing
688 /// situation, where the type of the closure is a double reference:
691 /// let a = [-1, 0, 1];
693 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
695 /// assert_eq!(iter.next(), Some(&0));
696 /// assert_eq!(iter.next(), Some(&1));
697 /// assert_eq!(iter.next(), None);
700 /// Stopping after an initial `false`:
703 /// let a = [-1, 0, 1, -2];
705 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
707 /// assert_eq!(iter.next(), Some(&0));
708 /// assert_eq!(iter.next(), Some(&1));
710 /// // while this would have been false, since we already got a false,
711 /// // skip_while() isn't used any more
712 /// assert_eq!(iter.next(), Some(&-2));
714 /// assert_eq!(iter.next(), None);
717 #[stable(feature = "rust1", since = "1.0.0")]
718 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
719 Self: Sized, P: FnMut(&Self::Item) -> bool,
721 SkipWhile{iter: self, flag: false, predicate: predicate}
724 /// Creates an iterator that yields elements based on a predicate.
726 /// `take_while()` takes a closure as an argument. It will call this
727 /// closure on each element of the iterator, and yield elements
728 /// while it returns `true`.
730 /// After `false` is returned, `take_while()`'s job is over, and the
731 /// rest of the elements are ignored.
738 /// let a = [-1i32, 0, 1];
740 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
742 /// assert_eq!(iter.next(), Some(&-1));
743 /// assert_eq!(iter.next(), None);
746 /// Because the closure passed to `take_while()` takes a reference, and many
747 /// iterators iterate over references, this leads to a possibly confusing
748 /// situation, where the type of the closure is a double reference:
751 /// let a = [-1, 0, 1];
753 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
755 /// assert_eq!(iter.next(), Some(&-1));
756 /// assert_eq!(iter.next(), None);
759 /// Stopping after an initial `false`:
762 /// let a = [-1, 0, 1, -2];
764 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
766 /// assert_eq!(iter.next(), Some(&-1));
768 /// // We have more elements that are less than zero, but since we already
769 /// // got a false, take_while() isn't used any more
770 /// assert_eq!(iter.next(), None);
773 /// Because `take_while()` needs to look at the value in order to see if it
774 /// should be included or not, consuming iterators will see that it is
778 /// let a = [1, 2, 3, 4];
779 /// let mut iter = a.into_iter();
781 /// let result: Vec<i32> = iter.by_ref()
782 /// .take_while(|n| **n != 3)
786 /// assert_eq!(result, &[1, 2]);
788 /// let result: Vec<i32> = iter.cloned().collect();
790 /// assert_eq!(result, &[4]);
793 /// The `3` is no longer there, because it was consumed in order to see if
794 /// the iteration should stop, but wasn't placed back into the iterator or
795 /// some similar thing.
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
799 Self: Sized, P: FnMut(&Self::Item) -> bool,
801 TakeWhile{iter: self, flag: false, predicate: predicate}
804 /// Creates an iterator that skips the first `n` elements.
806 /// After they have been consumed, the rest of the elements are yielded.
813 /// let a = [1, 2, 3];
815 /// let mut iter = a.iter().skip(2);
817 /// assert_eq!(iter.next(), Some(&3));
818 /// assert_eq!(iter.next(), None);
821 #[stable(feature = "rust1", since = "1.0.0")]
822 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
823 Skip{iter: self, n: n}
826 /// Creates an iterator that yields its first `n` elements.
833 /// let a = [1, 2, 3];
835 /// let mut iter = a.iter().take(2);
837 /// assert_eq!(iter.next(), Some(&1));
838 /// assert_eq!(iter.next(), Some(&2));
839 /// assert_eq!(iter.next(), None);
842 /// `take()` is often used with an infinite iterator, to make it finite:
845 /// let mut iter = (0..).take(3);
847 /// assert_eq!(iter.next(), Some(0));
848 /// assert_eq!(iter.next(), Some(1));
849 /// assert_eq!(iter.next(), Some(2));
850 /// assert_eq!(iter.next(), None);
853 #[stable(feature = "rust1", since = "1.0.0")]
854 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
855 Take{iter: self, n: n}
858 /// An iterator adaptor similar to [`fold()`] that holds internal state and
859 /// produces a new iterator.
861 /// [`fold()`]: #method.fold
863 /// `scan()` takes two arguments: an initial value which seeds the internal
864 /// state, and a closure with two arguments, the first being a mutable
865 /// reference to the internal state and the second an iterator element.
866 /// The closure can assign to the internal state to share state between
869 /// On iteration, the closure will be applied to each element of the
870 /// iterator and the return value from the closure, an [`Option`], is
871 /// yielded by the iterator.
873 /// [`Option`]: ../../std/option/enum.Option.html
880 /// let a = [1, 2, 3];
882 /// let mut iter = a.iter().scan(1, |state, &x| {
883 /// // each iteration, we'll multiply the state by the element
884 /// *state = *state * x;
886 /// // the value passed on to the next iteration
890 /// assert_eq!(iter.next(), Some(1));
891 /// assert_eq!(iter.next(), Some(2));
892 /// assert_eq!(iter.next(), Some(6));
893 /// assert_eq!(iter.next(), None);
896 #[stable(feature = "rust1", since = "1.0.0")]
897 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
898 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
900 Scan{iter: self, f: f, state: initial_state}
903 /// Creates an iterator that works like map, but flattens nested structure.
905 /// The [`map()`] adapter is very useful, but only when the closure
906 /// argument produces values. If it produces an iterator instead, there's
907 /// an extra layer of indirection. `flat_map()` will remove this extra layer
910 /// [`map()`]: #method.map
912 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
913 /// one item for each element, and `flat_map()`'s closure returns an
914 /// iterator for each element.
921 /// let words = ["alpha", "beta", "gamma"];
923 /// // chars() returns an iterator
924 /// let merged: String = words.iter()
925 /// .flat_map(|s| s.chars())
927 /// assert_eq!(merged, "alphabetagamma");
930 #[stable(feature = "rust1", since = "1.0.0")]
931 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
932 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
934 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
937 /// Creates an iterator which ends after the first `None`.
939 /// After an iterator returns `None`, future calls may or may not yield
940 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
941 /// `None` is given, it will always return `None` forever.
948 /// // an iterator which alternates between Some and None
949 /// struct Alternate {
953 /// impl Iterator for Alternate {
956 /// fn next(&mut self) -> Option<i32> {
957 /// let val = self.state;
958 /// self.state = self.state + 1;
960 /// // if it's even, Some(i32), else None
961 /// if val % 2 == 0 {
969 /// let mut iter = Alternate { state: 0 };
971 /// // we can see our iterator going back and forth
972 /// assert_eq!(iter.next(), Some(0));
973 /// assert_eq!(iter.next(), None);
974 /// assert_eq!(iter.next(), Some(2));
975 /// assert_eq!(iter.next(), None);
977 /// // however, once we fuse it...
978 /// let mut iter = iter.fuse();
980 /// assert_eq!(iter.next(), Some(4));
981 /// assert_eq!(iter.next(), None);
983 /// // it will always return None after the first time.
984 /// assert_eq!(iter.next(), None);
985 /// assert_eq!(iter.next(), None);
986 /// assert_eq!(iter.next(), None);
989 #[stable(feature = "rust1", since = "1.0.0")]
990 fn fuse(self) -> Fuse<Self> where Self: Sized {
991 Fuse{iter: self, done: false}
994 /// Do something with each element of an iterator, passing the value on.
996 /// When using iterators, you'll often chain several of them together.
997 /// While working on such code, you might want to check out what's
998 /// happening at various parts in the pipeline. To do that, insert
999 /// a call to `inspect()`.
1001 /// It's much more common for `inspect()` to be used as a debugging tool
1002 /// than to exist in your final code, but never say never.
1009 /// let a = [1, 4, 2, 3];
1011 /// // this iterator sequence is complex.
1012 /// let sum = a.iter()
1014 /// .filter(|&x| x % 2 == 0)
1015 /// .fold(0, |sum, i| sum + i);
1017 /// println!("{}", sum);
1019 /// // let's add some inspect() calls to investigate what's happening
1020 /// let sum = a.iter()
1022 /// .inspect(|x| println!("about to filter: {}", x))
1023 /// .filter(|&x| x % 2 == 0)
1024 /// .inspect(|x| println!("made it through filter: {}", x))
1025 /// .fold(0, |sum, i| sum + i);
1027 /// println!("{}", sum);
1030 /// This will print:
1033 /// about to filter: 1
1034 /// about to filter: 4
1035 /// made it through filter: 4
1036 /// about to filter: 2
1037 /// made it through filter: 2
1038 /// about to filter: 3
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1044 Self: Sized, F: FnMut(&Self::Item),
1046 Inspect{iter: self, f: f}
1049 /// Borrows an iterator, rather than consuming it.
1051 /// This is useful to allow applying iterator adaptors while still
1052 /// retaining ownership of the original iterator.
1059 /// let a = [1, 2, 3];
1061 /// let iter = a.into_iter();
1063 /// let sum: i32 = iter.take(5)
1064 /// .fold(0, |acc, &i| acc + i );
1066 /// assert_eq!(sum, 6);
1068 /// // if we try to use iter again, it won't work. The following line
1069 /// // gives "error: use of moved value: `iter`
1070 /// // assert_eq!(iter.next(), None);
1072 /// // let's try that again
1073 /// let a = [1, 2, 3];
1075 /// let mut iter = a.into_iter();
1077 /// // instead, we add in a .by_ref()
1078 /// let sum: i32 = iter.by_ref()
1080 /// .fold(0, |acc, &i| acc + i );
1082 /// assert_eq!(sum, 3);
1084 /// // now this is just fine:
1085 /// assert_eq!(iter.next(), Some(&3));
1086 /// assert_eq!(iter.next(), None);
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1091 /// Transforms an iterator into a collection.
1093 /// `collect()` can take anything iterable, and turn it into a relevant
1094 /// collection. This is one of the more powerful methods in the standard
1095 /// library, used in a variety of contexts.
1097 /// The most basic pattern in which `collect()` is used is to turn one
1098 /// collection into another. You take a collection, call `iter()` on it,
1099 /// do a bunch of transformations, and then `collect()` at the end.
1101 /// One of the keys to `collect()`'s power is that many things you might
1102 /// not think of as 'collections' actually are. For example, a [`String`]
1103 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1104 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1107 /// [`String`]: ../../std/string/struct.String.html
1108 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1109 /// [`char`]: ../../std/primitive.char.html
1111 /// Because `collect()` is so general, it can cause problems with type
1112 /// inference. As such, `collect()` is one of the few times you'll see
1113 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1114 /// helps the inference algorithm understand specifically which collection
1115 /// you're trying to collect into.
1122 /// let a = [1, 2, 3];
1124 /// let doubled: Vec<i32> = a.iter()
1125 /// .map(|&x| x * 2)
1128 /// assert_eq!(vec![2, 4, 6], doubled);
1131 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1132 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1134 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1137 /// use std::collections::VecDeque;
1139 /// let a = [1, 2, 3];
1141 /// let doubled: VecDeque<i32> = a.iter()
1142 /// .map(|&x| x * 2)
1145 /// assert_eq!(2, doubled[0]);
1146 /// assert_eq!(4, doubled[1]);
1147 /// assert_eq!(6, doubled[2]);
1150 /// Using the 'turbofish' instead of annotating `doubled`:
1153 /// let a = [1, 2, 3];
1155 /// let doubled = a.iter()
1156 /// .map(|&x| x * 2)
1157 /// .collect::<Vec<i32>>();
1159 /// assert_eq!(vec![2, 4, 6], doubled);
1162 /// Because `collect()` cares about what you're collecting into, you can
1163 /// still use a partial type hint, `_`, with the turbofish:
1166 /// let a = [1, 2, 3];
1168 /// let doubled = a.iter()
1169 /// .map(|&x| x * 2)
1170 /// .collect::<Vec<_>>();
1172 /// assert_eq!(vec![2, 4, 6], doubled);
1175 /// Using `collect()` to make a [`String`]:
1178 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1180 /// let hello: String = chars.iter()
1181 /// .map(|&x| x as u8)
1182 /// .map(|x| (x + 1) as char)
1185 /// assert_eq!("hello", hello);
1188 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1189 /// see if any of them failed:
1192 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1194 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1196 /// // gives us the first error
1197 /// assert_eq!(Err("nope"), result);
1199 /// let results = [Ok(1), Ok(3)];
1201 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1203 /// // gives us the list of answers
1204 /// assert_eq!(Ok(vec![1, 3]), result);
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1209 FromIterator::from_iter(self)
1212 /// Consumes an iterator, creating two collections from it.
1214 /// The predicate passed to `partition()` can return `true`, or `false`.
1215 /// `partition()` returns a pair, all of the elements for which it returned
1216 /// `true`, and all of the elements for which it returned `false`.
1223 /// let a = [1, 2, 3];
1225 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1226 /// .partition(|&n| n % 2 == 0);
1228 /// assert_eq!(even, vec![2]);
1229 /// assert_eq!(odd, vec![1, 3]);
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 fn partition<B, F>(self, mut f: F) -> (B, B) where
1234 B: Default + Extend<Self::Item>,
1235 F: FnMut(&Self::Item) -> bool
1237 let mut left: B = Default::default();
1238 let mut right: B = Default::default();
1242 left.extend(Some(x))
1244 right.extend(Some(x))
1251 /// An iterator adaptor that applies a function, producing a single, final value.
1253 /// `fold()` takes two arguments: an initial value, and a closure with two
1254 /// arguments: an 'accumulator', and an element. The closure returns the value that
1255 /// the accumulator should have for the next iteration.
1257 /// The initial value is the value the accumulator will have on the first
1260 /// After applying this closure to every element of the iterator, `fold()`
1261 /// returns the accumulator.
1263 /// This operation is sometimes called 'reduce' or 'inject'.
1265 /// Folding is useful whenever you have a collection of something, and want
1266 /// to produce a single value from it.
1273 /// let a = [1, 2, 3];
1275 /// // the sum of all of the elements of a
1276 /// let sum = a.iter()
1277 /// .fold(0, |acc, &x| acc + x);
1279 /// assert_eq!(sum, 6);
1282 /// Let's walk through each step of the iteration here:
1284 /// | element | acc | x | result |
1285 /// |---------|-----|---|--------|
1287 /// | 1 | 0 | 1 | 1 |
1288 /// | 2 | 1 | 2 | 3 |
1289 /// | 3 | 3 | 3 | 6 |
1291 /// And so, our final result, `6`.
1293 /// It's common for people who haven't used iterators a lot to
1294 /// use a `for` loop with a list of things to build up a result. Those
1295 /// can be turned into `fold()`s:
1298 /// let numbers = [1, 2, 3, 4, 5];
1300 /// let mut result = 0;
1303 /// for i in &numbers {
1304 /// result = result + i;
1308 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1310 /// // they're the same
1311 /// assert_eq!(result, result2);
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 fn fold<B, F>(self, init: B, mut f: F) -> B where
1316 Self: Sized, F: FnMut(B, Self::Item) -> B,
1318 let mut accum = init;
1320 accum = f(accum, x);
1325 /// Tests if every element of the iterator matches a predicate.
1327 /// `all()` takes a closure that returns `true` or `false`. It applies
1328 /// this closure to each element of the iterator, and if they all return
1329 /// `true`, then so does `all()`. If any of them return `false`, it
1330 /// returns `false`.
1332 /// `all()` is short-circuiting; in other words, it will stop processing
1333 /// as soon as it finds a `false`, given that no matter what else happens,
1334 /// the result will also be `false`.
1336 /// An empty iterator returns `true`.
1343 /// let a = [1, 2, 3];
1345 /// assert!(a.iter().all(|&x| x > 0));
1347 /// assert!(!a.iter().all(|&x| x > 2));
1350 /// Stopping at the first `false`:
1353 /// let a = [1, 2, 3];
1355 /// let mut iter = a.iter();
1357 /// assert!(!iter.all(|&x| x != 2));
1359 /// // we can still use `iter`, as there are more elements.
1360 /// assert_eq!(iter.next(), Some(&3));
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 fn all<F>(&mut self, mut f: F) -> bool where
1365 Self: Sized, F: FnMut(Self::Item) -> bool
1375 /// Tests if any element of the iterator matches a predicate.
1377 /// `any()` takes a closure that returns `true` or `false`. It applies
1378 /// this closure to each element of the iterator, and if any of them return
1379 /// `true`, then so does `any()`. If they all return `false`, it
1380 /// returns `false`.
1382 /// `any()` is short-circuiting; in other words, it will stop processing
1383 /// as soon as it finds a `true`, given that no matter what else happens,
1384 /// the result will also be `true`.
1386 /// An empty iterator returns `false`.
1393 /// let a = [1, 2, 3];
1395 /// assert!(a.iter().any(|&x| x > 0));
1397 /// assert!(!a.iter().any(|&x| x > 5));
1400 /// Stopping at the first `true`:
1403 /// let a = [1, 2, 3];
1405 /// let mut iter = a.iter();
1407 /// assert!(iter.any(|&x| x != 2));
1409 /// // we can still use `iter`, as there are more elements.
1410 /// assert_eq!(iter.next(), Some(&2));
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 fn any<F>(&mut self, mut f: F) -> bool where
1416 F: FnMut(Self::Item) -> bool
1426 /// Searches for an element of an iterator that satisfies a predicate.
1428 /// `find()` takes a closure that returns `true` or `false`. It applies
1429 /// this closure to each element of the iterator, and if any of them return
1430 /// `true`, then `find()` returns `Some(element)`. If they all return
1431 /// `false`, it returns `None`.
1433 /// `find()` is short-circuiting; in other words, it will stop processing
1434 /// as soon as the closure returns `true`.
1436 /// Because `find()` takes a reference, and many iterators iterate over
1437 /// references, this leads to a possibly confusing situation where the
1438 /// argument is a double reference. You can see this effect in the
1439 /// examples below, with `&&x`.
1446 /// let a = [1, 2, 3];
1448 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1450 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1453 /// Stopping at the first `true`:
1456 /// let a = [1, 2, 3];
1458 /// let mut iter = a.iter();
1460 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1462 /// // we can still use `iter`, as there are more elements.
1463 /// assert_eq!(iter.next(), Some(&3));
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1469 P: FnMut(&Self::Item) -> bool,
1472 if predicate(&x) { return Some(x) }
1477 /// Searches for an element in an iterator, returning its index.
1479 /// `position()` takes a closure that returns `true` or `false`. It applies
1480 /// this closure to each element of the iterator, and if one of them
1481 /// returns `true`, then `position()` returns `Some(index)`. If all of
1482 /// them return `false`, it returns `None`.
1484 /// `position()` is short-circuiting; in other words, it will stop
1485 /// processing as soon as it finds a `true`.
1487 /// # Overflow Behavior
1489 /// The method does no guarding against overflows, so if there are more
1490 /// than `usize::MAX` non-matching elements, it either produces the wrong
1491 /// result or panics. If debug assertions are enabled, a panic is
1496 /// This function might panic if the iterator has more than `usize::MAX`
1497 /// non-matching elements.
1504 /// let a = [1, 2, 3];
1506 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1508 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1511 /// Stopping at the first `true`:
1514 /// let a = [1, 2, 3];
1516 /// let mut iter = a.iter();
1518 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1520 /// // we can still use `iter`, as there are more elements.
1521 /// assert_eq!(iter.next(), Some(&3));
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1527 P: FnMut(Self::Item) -> bool,
1529 // `enumerate` might overflow.
1530 for (i, x) in self.enumerate() {
1538 /// Searches for an element in an iterator from the right, returning its
1541 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1542 /// this closure to each element of the iterator, starting from the end,
1543 /// and if one of them returns `true`, then `rposition()` returns
1544 /// `Some(index)`. If all of them return `false`, it returns `None`.
1546 /// `rposition()` is short-circuiting; in other words, it will stop
1547 /// processing as soon as it finds a `true`.
1554 /// let a = [1, 2, 3];
1556 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1558 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1561 /// Stopping at the first `true`:
1564 /// let a = [1, 2, 3];
1566 /// let mut iter = a.iter();
1568 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1570 /// // we can still use `iter`, as there are more elements.
1571 /// assert_eq!(iter.next(), Some(&1));
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1576 P: FnMut(Self::Item) -> bool,
1577 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1579 let mut i = self.len();
1581 while let Some(v) = self.next_back() {
1585 // No need for an overflow check here, because `ExactSizeIterator`
1586 // implies that the number of elements fits into a `usize`.
1592 /// Returns the maximum element of an iterator.
1594 /// If the two elements are equally maximum, the latest element is
1602 /// let a = [1, 2, 3];
1604 /// assert_eq!(a.iter().max(), Some(&3));
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1612 // switch to y even if it is only equal, to preserve
1614 |_, x, _, y| *x <= *y)
1618 /// Returns the minimum element of an iterator.
1620 /// If the two elements are equally minimum, the first element is
1628 /// let a = [1, 2, 3];
1630 /// assert_eq!(a.iter().min(), Some(&1));
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1638 // only switch to y if it is strictly smaller, to
1639 // preserve stability.
1640 |_, x, _, y| *x > *y)
1644 /// Returns the element that gives the maximum value from the
1645 /// specified function.
1647 /// Returns the rightmost element if the comparison determines two elements
1648 /// to be equally maximum.
1653 /// let a = [-3_i32, 0, 1, 5, -10];
1654 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1657 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1658 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1659 where Self: Sized, F: FnMut(&Self::Item) -> B,
1663 // switch to y even if it is only equal, to preserve
1665 |x_p, _, y_p, _| x_p <= y_p)
1669 /// Returns the element that gives the minimum value from the
1670 /// specified function.
1672 /// Returns the latest element if the comparison determines two elements
1673 /// to be equally minimum.
1678 /// let a = [-3_i32, 0, 1, 5, -10];
1679 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1681 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1682 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1683 where Self: Sized, F: FnMut(&Self::Item) -> B,
1687 // only switch to y if it is strictly smaller, to
1688 // preserve stability.
1689 |x_p, _, y_p, _| x_p > y_p)
1693 /// Reverses an iterator's direction.
1695 /// Usually, iterators iterate from left to right. After using `rev()`,
1696 /// an iterator will instead iterate from right to left.
1698 /// This is only possible if the iterator has an end, so `rev()` only
1699 /// works on [`DoubleEndedIterator`]s.
1701 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1706 /// let a = [1, 2, 3];
1708 /// let mut iter = a.iter().rev();
1710 /// assert_eq!(iter.next(), Some(&3));
1711 /// assert_eq!(iter.next(), Some(&2));
1712 /// assert_eq!(iter.next(), Some(&1));
1714 /// assert_eq!(iter.next(), None);
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1722 /// Converts an iterator of pairs into a pair of containers.
1724 /// `unzip()` consumes an entire iterator of pairs, producing two
1725 /// collections: one from the left elements of the pairs, and one
1726 /// from the right elements.
1728 /// This function is, in some sense, the opposite of [`zip()`].
1730 /// [`zip()`]: #method.zip
1737 /// let a = [(1, 2), (3, 4)];
1739 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1741 /// assert_eq!(left, [1, 3]);
1742 /// assert_eq!(right, [2, 4]);
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1746 FromA: Default + Extend<A>,
1747 FromB: Default + Extend<B>,
1748 Self: Sized + Iterator<Item=(A, B)>,
1750 let mut ts: FromA = Default::default();
1751 let mut us: FromB = Default::default();
1753 for (t, u) in self {
1761 /// Creates an iterator which `clone()`s all of its elements.
1763 /// This is useful when you have an iterator over `&T`, but you need an
1764 /// iterator over `T`.
1771 /// let a = [1, 2, 3];
1773 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1775 /// // cloned is the same as .map(|&x| x), for integers
1776 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1778 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1779 /// assert_eq!(v_map, vec![1, 2, 3]);
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1783 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1788 /// Repeats an iterator endlessly.
1790 /// Instead of stopping at `None`, the iterator will instead start again,
1791 /// from the beginning. After iterating again, it will start at the
1792 /// beginning again. And again. And again. Forever.
1799 /// let a = [1, 2, 3];
1801 /// let mut it = a.iter().cycle();
1803 /// assert_eq!(it.next(), Some(&1));
1804 /// assert_eq!(it.next(), Some(&2));
1805 /// assert_eq!(it.next(), Some(&3));
1806 /// assert_eq!(it.next(), Some(&1));
1807 /// assert_eq!(it.next(), Some(&2));
1808 /// assert_eq!(it.next(), Some(&3));
1809 /// assert_eq!(it.next(), Some(&1));
1811 #[stable(feature = "rust1", since = "1.0.0")]
1813 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1814 Cycle{orig: self.clone(), iter: self}
1817 /// Sums the elements of an iterator.
1819 /// Takes each element, adds them together, and returns the result.
1821 /// An empty iterator returns the zero value of the type.
1828 /// #![feature(iter_arith)]
1830 /// let a = [1, 2, 3];
1831 /// let sum: i32 = a.iter().sum();
1833 /// assert_eq!(sum, 6);
1835 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
1837 fn sum<S>(self) -> S where
1838 S: Add<Self::Item, Output=S> + Zero,
1841 self.fold(Zero::zero(), |s, e| s + e)
1844 /// Iterates over the entire iterator, multiplying all the elements
1846 /// An empty iterator returns the one value of the type.
1851 /// #![feature(iter_arith)]
1853 /// fn factorial(n: u32) -> u32 {
1854 /// (1..).take_while(|&i| i <= n).product()
1856 /// assert_eq!(factorial(0), 1);
1857 /// assert_eq!(factorial(1), 1);
1858 /// assert_eq!(factorial(5), 120);
1860 #[unstable(feature="iter_arith", reason = "bounds recently changed",
1862 fn product<P>(self) -> P where
1863 P: Mul<Self::Item, Output=P> + One,
1866 self.fold(One::one(), |p, e| p * e)
1869 /// Lexicographically compares the elements of this `Iterator` with those
1871 #[stable(feature = "iter_order", since = "1.5.0")]
1872 fn cmp<I>(mut self, other: I) -> Ordering where
1873 I: IntoIterator<Item = Self::Item>,
1877 let mut other = other.into_iter();
1880 match (self.next(), other.next()) {
1881 (None, None) => return Ordering::Equal,
1882 (None, _ ) => return Ordering::Less,
1883 (_ , None) => return Ordering::Greater,
1884 (Some(x), Some(y)) => match x.cmp(&y) {
1885 Ordering::Equal => (),
1886 non_eq => return non_eq,
1892 /// Lexicographically compares the elements of this `Iterator` with those
1894 #[stable(feature = "iter_order", since = "1.5.0")]
1895 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1897 Self::Item: PartialOrd<I::Item>,
1900 let mut other = other.into_iter();
1903 match (self.next(), other.next()) {
1904 (None, None) => return Some(Ordering::Equal),
1905 (None, _ ) => return Some(Ordering::Less),
1906 (_ , None) => return Some(Ordering::Greater),
1907 (Some(x), Some(y)) => match x.partial_cmp(&y) {
1908 Some(Ordering::Equal) => (),
1909 non_eq => return non_eq,
1915 /// Determines if the elements of this `Iterator` are equal to those of
1917 #[stable(feature = "iter_order", since = "1.5.0")]
1918 fn eq<I>(mut self, other: I) -> bool where
1920 Self::Item: PartialEq<I::Item>,
1923 let mut other = other.into_iter();
1926 match (self.next(), other.next()) {
1927 (None, None) => return true,
1928 (None, _) | (_, None) => return false,
1929 (Some(x), Some(y)) => if x != y { return false },
1934 /// Determines if the elements of this `Iterator` are unequal to those of
1936 #[stable(feature = "iter_order", since = "1.5.0")]
1937 fn ne<I>(mut self, other: I) -> bool where
1939 Self::Item: PartialEq<I::Item>,
1942 let mut other = other.into_iter();
1945 match (self.next(), other.next()) {
1946 (None, None) => return false,
1947 (None, _) | (_, None) => return true,
1948 (Some(x), Some(y)) => if x.ne(&y) { return true },
1953 /// Determines if the elements of this `Iterator` are lexicographically
1954 /// less than those of another.
1955 #[stable(feature = "iter_order", since = "1.5.0")]
1956 fn lt<I>(mut self, other: I) -> bool where
1958 Self::Item: PartialOrd<I::Item>,
1961 let mut other = other.into_iter();
1964 match (self.next(), other.next()) {
1965 (None, None) => return false,
1966 (None, _ ) => return true,
1967 (_ , None) => return false,
1968 (Some(x), Some(y)) => {
1969 match x.partial_cmp(&y) {
1970 Some(Ordering::Less) => return true,
1971 Some(Ordering::Equal) => {}
1972 Some(Ordering::Greater) => return false,
1973 None => return false,
1980 /// Determines if the elements of this `Iterator` are lexicographically
1981 /// less or equal to those of another.
1982 #[stable(feature = "iter_order", since = "1.5.0")]
1983 fn le<I>(mut self, other: I) -> bool where
1985 Self::Item: PartialOrd<I::Item>,
1988 let mut other = other.into_iter();
1991 match (self.next(), other.next()) {
1992 (None, None) => return true,
1993 (None, _ ) => return true,
1994 (_ , None) => return false,
1995 (Some(x), Some(y)) => {
1996 match x.partial_cmp(&y) {
1997 Some(Ordering::Less) => return true,
1998 Some(Ordering::Equal) => {}
1999 Some(Ordering::Greater) => return false,
2000 None => return false,
2007 /// Determines if the elements of this `Iterator` are lexicographically
2008 /// greater than those of another.
2009 #[stable(feature = "iter_order", since = "1.5.0")]
2010 fn gt<I>(mut self, other: I) -> bool where
2012 Self::Item: PartialOrd<I::Item>,
2015 let mut other = other.into_iter();
2018 match (self.next(), other.next()) {
2019 (None, None) => return false,
2020 (None, _ ) => return false,
2021 (_ , None) => return true,
2022 (Some(x), Some(y)) => {
2023 match x.partial_cmp(&y) {
2024 Some(Ordering::Less) => return false,
2025 Some(Ordering::Equal) => {}
2026 Some(Ordering::Greater) => return true,
2027 None => return false,
2034 /// Determines if the elements of this `Iterator` are lexicographically
2035 /// greater than or equal to those of another.
2036 #[stable(feature = "iter_order", since = "1.5.0")]
2037 fn ge<I>(mut self, other: I) -> bool where
2039 Self::Item: PartialOrd<I::Item>,
2042 let mut other = other.into_iter();
2045 match (self.next(), other.next()) {
2046 (None, None) => return true,
2047 (None, _ ) => return false,
2048 (_ , None) => return true,
2049 (Some(x), Some(y)) => {
2050 match x.partial_cmp(&y) {
2051 Some(Ordering::Less) => return false,
2052 Some(Ordering::Equal) => {}
2053 Some(Ordering::Greater) => return true,
2054 None => return false,
2062 /// Select an element from an iterator based on the given projection
2063 /// and "comparison" function.
2065 /// This is an idiosyncratic helper to try to factor out the
2066 /// commonalities of {max,min}{,_by}. In particular, this avoids
2067 /// having to implement optimizations several times.
2069 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2071 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2073 FProj: FnMut(&I::Item) -> B,
2074 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2076 // start with the first element as our selection. This avoids
2077 // having to use `Option`s inside the loop, translating to a
2078 // sizeable performance gain (6x in one case).
2079 it.next().map(|mut sel| {
2080 let mut sel_p = f_proj(&sel);
2083 let x_p = f_proj(&x);
2084 if f_cmp(&sel_p, &sel, &x_p, &x) {
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2095 type Item = I::Item;
2096 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2097 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }