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}
;
16 use ops
::{Add, FnMut, Mul}
;
17 use option
::Option
::{self, Some, None}
;
20 use super::{Chain
, Cycle
, Cloned
, Enumerate
, Filter
, FilterMap
, FlatMap
, Fuse
,
21 Inspect
, Map
, Peekable
, Scan
, Skip
, SkipWhile
, Take
, TakeWhile
, Rev
,
23 use super::ChainState
;
24 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 #[stable(feature = "rust1", since = "1.0.0")]
176 fn count(self) -> usize where Self: Sized
{
178 self.fold(0, |cnt
, _
| cnt
+ 1)
181 /// Consumes the iterator, returning the last element.
183 /// This method will evaluate the iterator until it returns `None`. While
184 /// doing so, it keeps track of the current element. After `None` is
185 /// returned, `last()` will then return the last element it saw.
192 /// let a = [1, 2, 3];
193 /// assert_eq!(a.iter().last(), Some(&3));
195 /// let a = [1, 2, 3, 4, 5];
196 /// assert_eq!(a.iter().last(), Some(&5));
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn last(self) -> Option
<Self::Item
> where Self: Sized
{
202 for x
in self { last = Some(x); }
206 /// Consumes the `n` first elements of the iterator, then returns the
209 /// This method will evaluate the iterator `n` times, discarding those elements.
210 /// After it does so, it will call [`next()`] and return its value.
212 /// [`next()`]: #tymethod.next
214 /// Like most indexing operations, the count starts from zero, so `nth(0)`
215 /// returns the first value, `nth(1)` the second, and so on.
217 /// `nth()` will return `None` if `n` is greater than or equal to the length of the
225 /// let a = [1, 2, 3];
226 /// assert_eq!(a.iter().nth(1), Some(&2));
229 /// Calling `nth()` multiple times doesn't rewind the iterator:
232 /// let a = [1, 2, 3];
234 /// let mut iter = a.iter();
236 /// assert_eq!(iter.nth(1), Some(&2));
237 /// assert_eq!(iter.nth(1), None);
240 /// Returning `None` if there are less than `n + 1` elements:
243 /// let a = [1, 2, 3];
244 /// assert_eq!(a.iter().nth(10), None);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 fn nth(&mut self, mut n
: usize) -> Option
<Self::Item
> where Self: Sized
{
250 if n
== 0 { return Some(x) }
256 /// Takes two iterators and creates a new iterator over both in sequence.
258 /// `chain()` will return a new iterator which will first iterate over
259 /// values from the first iterator and then over values from the second
262 /// In other words, it links two iterators together, in a chain. 🔗
269 /// let a1 = [1, 2, 3];
270 /// let a2 = [4, 5, 6];
272 /// let mut iter = a1.iter().chain(a2.iter());
274 /// assert_eq!(iter.next(), Some(&1));
275 /// assert_eq!(iter.next(), Some(&2));
276 /// assert_eq!(iter.next(), Some(&3));
277 /// assert_eq!(iter.next(), Some(&4));
278 /// assert_eq!(iter.next(), Some(&5));
279 /// assert_eq!(iter.next(), Some(&6));
280 /// assert_eq!(iter.next(), None);
283 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
284 /// anything that can be converted into an [`Iterator`], not just an
285 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
286 /// [`IntoIterator`], and so can be passed to `chain()` directly:
288 /// [`IntoIterator`]: trait.IntoIterator.html
289 /// [`Iterator`]: trait.Iterator.html
292 /// let s1 = &[1, 2, 3];
293 /// let s2 = &[4, 5, 6];
295 /// let mut iter = s1.iter().chain(s2);
297 /// assert_eq!(iter.next(), Some(&1));
298 /// assert_eq!(iter.next(), Some(&2));
299 /// assert_eq!(iter.next(), Some(&3));
300 /// assert_eq!(iter.next(), Some(&4));
301 /// assert_eq!(iter.next(), Some(&5));
302 /// assert_eq!(iter.next(), Some(&6));
303 /// assert_eq!(iter.next(), None);
306 #[stable(feature = "rust1", since = "1.0.0")]
307 fn chain
<U
>(self, other
: U
) -> Chain
<Self, U
::IntoIter
> where
308 Self: Sized
, U
: IntoIterator
<Item
=Self::Item
>,
310 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
313 /// 'Zips up' two iterators into a single iterator of pairs.
315 /// `zip()` returns a new iterator that will iterate over two other
316 /// iterators, returning a tuple where the first element comes from the
317 /// first iterator, and the second element comes from the second iterator.
319 /// In other words, it zips two iterators together, into a single one.
321 /// When either iterator returns `None`, all further calls to `next()`
322 /// will return `None`.
329 /// let a1 = [1, 2, 3];
330 /// let a2 = [4, 5, 6];
332 /// let mut iter = a1.iter().zip(a2.iter());
334 /// assert_eq!(iter.next(), Some((&1, &4)));
335 /// assert_eq!(iter.next(), Some((&2, &5)));
336 /// assert_eq!(iter.next(), Some((&3, &6)));
337 /// assert_eq!(iter.next(), None);
340 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
341 /// anything that can be converted into an [`Iterator`], not just an
342 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
343 /// [`IntoIterator`], and so can be passed to `zip()` directly:
345 /// [`IntoIterator`]: trait.IntoIterator.html
346 /// [`Iterator`]: trait.Iterator.html
349 /// let s1 = &[1, 2, 3];
350 /// let s2 = &[4, 5, 6];
352 /// let mut iter = s1.iter().zip(s2);
354 /// assert_eq!(iter.next(), Some((&1, &4)));
355 /// assert_eq!(iter.next(), Some((&2, &5)));
356 /// assert_eq!(iter.next(), Some((&3, &6)));
357 /// assert_eq!(iter.next(), None);
360 /// `zip()` is often used to zip an infinite iterator to a finite one.
361 /// This works because the finite iterator will eventually return `None`,
362 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
365 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
367 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
369 /// assert_eq!((0, 'f'), enumerate[0]);
370 /// assert_eq!((0, 'f'), zipper[0]);
372 /// assert_eq!((1, 'o'), enumerate[1]);
373 /// assert_eq!((1, 'o'), zipper[1]);
375 /// assert_eq!((2, 'o'), enumerate[2]);
376 /// assert_eq!((2, 'o'), zipper[2]);
379 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
381 #[stable(feature = "rust1", since = "1.0.0")]
382 fn zip
<U
>(self, other
: U
) -> Zip
<Self, U
::IntoIter
> where
383 Self: Sized
, U
: IntoIterator
385 Zip{a: self, b: other.into_iter()}
388 /// Takes a closure and creates an iterator which calls that closure on each
391 /// `map()` transforms one iterator into another, by means of its argument:
392 /// something that implements `FnMut`. It produces a new iterator which
393 /// calls this closure on each element of the original iterator.
395 /// If you are good at thinking in types, you can think of `map()` like this:
396 /// If you have an iterator that gives you elements of some type `A`, and
397 /// you want an iterator of some other type `B`, you can use `map()`,
398 /// passing a closure that takes an `A` and returns a `B`.
400 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
401 /// lazy, it is best used when you're already working with other iterators.
402 /// If you're doing some sort of looping for a side effect, it's considered
403 /// more idiomatic to use [`for`] than `map()`.
405 /// [`for`]: ../../book/loops.html#for
412 /// let a = [1, 2, 3];
414 /// let mut iter = a.into_iter().map(|x| 2 * x);
416 /// assert_eq!(iter.next(), Some(2));
417 /// assert_eq!(iter.next(), Some(4));
418 /// assert_eq!(iter.next(), Some(6));
419 /// assert_eq!(iter.next(), None);
422 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
425 /// # #![allow(unused_must_use)]
426 /// // don't do this:
427 /// (0..5).map(|x| println!("{}", x));
429 /// // it won't even execute, as it is lazy. Rust will warn you about this.
431 /// // Instead, use for:
433 /// println!("{}", x);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 fn map
<B
, F
>(self, f
: F
) -> Map
<Self, F
> where
439 Self: Sized
, F
: FnMut(Self::Item
) -> B
,
441 Map{iter: self, f: f}
444 /// Creates an iterator which uses a closure to determine if an element
445 /// should be yielded.
447 /// The closure must return `true` or `false`. `filter()` creates an
448 /// iterator which calls this closure on each element. If the closure
449 /// returns `true`, then the element is returned. If the closure returns
450 /// `false`, it will try again, and call the closure on the next element,
451 /// seeing if it passes the test.
458 /// let a = [0i32, 1, 2];
460 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
462 /// assert_eq!(iter.next(), Some(&1));
463 /// assert_eq!(iter.next(), Some(&2));
464 /// assert_eq!(iter.next(), None);
467 /// Because the closure passed to `filter()` takes a reference, and many
468 /// iterators iterate over references, this leads to a possibly confusing
469 /// situation, where the type of the closure is a double reference:
472 /// let a = [0, 1, 2];
474 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
476 /// assert_eq!(iter.next(), Some(&2));
477 /// assert_eq!(iter.next(), None);
480 /// It's common to instead use destructuring on the argument to strip away
484 /// let a = [0, 1, 2];
486 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
488 /// assert_eq!(iter.next(), Some(&2));
489 /// assert_eq!(iter.next(), None);
495 /// let a = [0, 1, 2];
497 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
499 /// assert_eq!(iter.next(), Some(&2));
500 /// assert_eq!(iter.next(), None);
505 #[stable(feature = "rust1", since = "1.0.0")]
506 fn filter
<P
>(self, predicate
: P
) -> Filter
<Self, P
> where
507 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
509 Filter{iter: self, predicate: predicate}
512 /// Creates an iterator that both filters and maps.
514 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
515 /// iterator which calls this closure on each element. If the closure
516 /// returns `Some(element)`, then that element is returned. If the
517 /// closure returns `None`, it will try again, and call the closure on the
518 /// next element, seeing if it will return `Some`.
520 /// [`Option<T>`]: ../../std/option/enum.Option.html
522 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
525 /// [`filter()`]: #method.filter
526 /// [`map()`]: #method.map
528 /// > If the closure returns `Some(element)`, then that element is returned.
530 /// In other words, it removes the [`Option<T>`] layer automatically. If your
531 /// mapping is already returning an [`Option<T>`] and you want to skip over
532 /// `None`s, then `filter_map()` is much, much nicer to use.
539 /// let a = ["1", "2", "lol"];
541 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
543 /// assert_eq!(iter.next(), Some(1));
544 /// assert_eq!(iter.next(), Some(2));
545 /// assert_eq!(iter.next(), None);
548 /// Here's the same example, but with [`filter()`] and [`map()`]:
551 /// let a = ["1", "2", "lol"];
553 /// let mut iter = a.iter()
554 /// .map(|s| s.parse().ok())
555 /// .filter(|s| s.is_some());
557 /// assert_eq!(iter.next(), Some(Some(1)));
558 /// assert_eq!(iter.next(), Some(Some(2)));
559 /// assert_eq!(iter.next(), None);
562 /// There's an extra layer of `Some` in there.
564 #[stable(feature = "rust1", since = "1.0.0")]
565 fn filter_map
<B
, F
>(self, f
: F
) -> FilterMap
<Self, F
> where
566 Self: Sized
, F
: FnMut(Self::Item
) -> Option
<B
>,
568 FilterMap { iter: self, f: f }
571 /// Creates an iterator which gives the current iteration count as well as
574 /// The iterator returned yields pairs `(i, val)`, where `i` is the
575 /// current index of iteration and `val` is the value returned by the
578 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
579 /// different sized integer, the [`zip()`] function provides similar
582 /// [`usize`]: ../../std/primitive.usize.html
583 /// [`zip()`]: #method.zip
585 /// # Overflow Behavior
587 /// The method does no guarding against overflows, so enumerating more than
588 /// [`usize::MAX`] elements either produces the wrong result or panics. If
589 /// debug assertions are enabled, a panic is guaranteed.
591 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
595 /// The returned iterator might panic if the to-be-returned index would
596 /// overflow a `usize`.
601 /// let a = ['a', 'b', 'c'];
603 /// let mut iter = a.iter().enumerate();
605 /// assert_eq!(iter.next(), Some((0, &'a')));
606 /// assert_eq!(iter.next(), Some((1, &'b')));
607 /// assert_eq!(iter.next(), Some((2, &'c')));
608 /// assert_eq!(iter.next(), None);
611 #[stable(feature = "rust1", since = "1.0.0")]
612 fn enumerate(self) -> Enumerate
<Self> where Self: Sized
{
613 Enumerate { iter: self, count: 0 }
616 /// Creates an iterator which can use `peek` to look at the next element of
617 /// the iterator without consuming it.
619 /// Adds a [`peek()`] method to an iterator. See its documentation for
620 /// more information.
622 /// Note that the underlying iterator is still advanced when `peek` is
623 /// called for the first time: In order to retrieve the next element,
624 /// `next` is called on the underlying iterator, hence any side effects of
625 /// the `next` method will occur.
627 /// [`peek()`]: struct.Peekable.html#method.peek
634 /// let xs = [1, 2, 3];
636 /// let mut iter = xs.iter().peekable();
638 /// // peek() lets us see into the future
639 /// assert_eq!(iter.peek(), Some(&&1));
640 /// assert_eq!(iter.next(), Some(&1));
642 /// assert_eq!(iter.next(), Some(&2));
644 /// // we can peek() multiple times, the iterator won't advance
645 /// assert_eq!(iter.peek(), Some(&&3));
646 /// assert_eq!(iter.peek(), Some(&&3));
648 /// assert_eq!(iter.next(), Some(&3));
650 /// // after the iterator is finished, so is peek()
651 /// assert_eq!(iter.peek(), None);
652 /// assert_eq!(iter.next(), None);
655 #[stable(feature = "rust1", since = "1.0.0")]
656 fn peekable(self) -> Peekable
<Self> where Self: Sized
{
657 Peekable{iter: self, peeked: None}
660 /// Creates an iterator that [`skip()`]s elements based on a predicate.
662 /// [`skip()`]: #method.skip
664 /// `skip_while()` takes a closure as an argument. It will call this
665 /// closure on each element of the iterator, and ignore elements
666 /// until it returns `false`.
668 /// After `false` is returned, `skip_while()`'s job is over, and the
669 /// rest of the elements are yielded.
676 /// let a = [-1i32, 0, 1];
678 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
680 /// assert_eq!(iter.next(), Some(&0));
681 /// assert_eq!(iter.next(), Some(&1));
682 /// assert_eq!(iter.next(), None);
685 /// Because the closure passed to `skip_while()` takes a reference, and many
686 /// iterators iterate over references, this leads to a possibly confusing
687 /// situation, where the type of the closure is a double reference:
690 /// let a = [-1, 0, 1];
692 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
694 /// assert_eq!(iter.next(), Some(&0));
695 /// assert_eq!(iter.next(), Some(&1));
696 /// assert_eq!(iter.next(), None);
699 /// Stopping after an initial `false`:
702 /// let a = [-1, 0, 1, -2];
704 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
706 /// assert_eq!(iter.next(), Some(&0));
707 /// assert_eq!(iter.next(), Some(&1));
709 /// // while this would have been false, since we already got a false,
710 /// // skip_while() isn't used any more
711 /// assert_eq!(iter.next(), Some(&-2));
713 /// assert_eq!(iter.next(), None);
716 #[stable(feature = "rust1", since = "1.0.0")]
717 fn skip_while
<P
>(self, predicate
: P
) -> SkipWhile
<Self, P
> where
718 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
720 SkipWhile{iter: self, flag: false, predicate: predicate}
723 /// Creates an iterator that yields elements based on a predicate.
725 /// `take_while()` takes a closure as an argument. It will call this
726 /// closure on each element of the iterator, and yield elements
727 /// while it returns `true`.
729 /// After `false` is returned, `take_while()`'s job is over, and the
730 /// rest of the elements are ignored.
737 /// let a = [-1i32, 0, 1];
739 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
741 /// assert_eq!(iter.next(), Some(&-1));
742 /// assert_eq!(iter.next(), None);
745 /// Because the closure passed to `take_while()` takes a reference, and many
746 /// iterators iterate over references, this leads to a possibly confusing
747 /// situation, where the type of the closure is a double reference:
750 /// let a = [-1, 0, 1];
752 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
754 /// assert_eq!(iter.next(), Some(&-1));
755 /// assert_eq!(iter.next(), None);
758 /// Stopping after an initial `false`:
761 /// let a = [-1, 0, 1, -2];
763 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
765 /// assert_eq!(iter.next(), Some(&-1));
767 /// // We have more elements that are less than zero, but since we already
768 /// // got a false, take_while() isn't used any more
769 /// assert_eq!(iter.next(), None);
772 /// Because `take_while()` needs to look at the value in order to see if it
773 /// should be included or not, consuming iterators will see that it is
777 /// let a = [1, 2, 3, 4];
778 /// let mut iter = a.into_iter();
780 /// let result: Vec<i32> = iter.by_ref()
781 /// .take_while(|n| **n != 3)
785 /// assert_eq!(result, &[1, 2]);
787 /// let result: Vec<i32> = iter.cloned().collect();
789 /// assert_eq!(result, &[4]);
792 /// The `3` is no longer there, because it was consumed in order to see if
793 /// the iteration should stop, but wasn't placed back into the iterator or
794 /// some similar thing.
796 #[stable(feature = "rust1", since = "1.0.0")]
797 fn take_while
<P
>(self, predicate
: P
) -> TakeWhile
<Self, P
> where
798 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
800 TakeWhile{iter: self, flag: false, predicate: predicate}
803 /// Creates an iterator that skips the first `n` elements.
805 /// After they have been consumed, the rest of the elements are yielded.
812 /// let a = [1, 2, 3];
814 /// let mut iter = a.iter().skip(2);
816 /// assert_eq!(iter.next(), Some(&3));
817 /// assert_eq!(iter.next(), None);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn skip(self, n
: usize) -> Skip
<Self> where Self: Sized
{
822 Skip{iter: self, n: n}
825 /// Creates an iterator that yields its first `n` elements.
832 /// let a = [1, 2, 3];
834 /// let mut iter = a.iter().take(2);
836 /// assert_eq!(iter.next(), Some(&1));
837 /// assert_eq!(iter.next(), Some(&2));
838 /// assert_eq!(iter.next(), None);
841 /// `take()` is often used with an infinite iterator, to make it finite:
844 /// let mut iter = (0..).take(3);
846 /// assert_eq!(iter.next(), Some(0));
847 /// assert_eq!(iter.next(), Some(1));
848 /// assert_eq!(iter.next(), Some(2));
849 /// assert_eq!(iter.next(), None);
852 #[stable(feature = "rust1", since = "1.0.0")]
853 fn take(self, n
: usize) -> Take
<Self> where Self: Sized
, {
854 Take{iter: self, n: n}
857 /// An iterator adaptor similar to [`fold()`] that holds internal state and
858 /// produces a new iterator.
860 /// [`fold()`]: #method.fold
862 /// `scan()` takes two arguments: an initial value which seeds the internal
863 /// state, and a closure with two arguments, the first being a mutable
864 /// reference to the internal state and the second an iterator element.
865 /// The closure can assign to the internal state to share state between
868 /// On iteration, the closure will be applied to each element of the
869 /// iterator and the return value from the closure, an [`Option`], is
870 /// yielded by the iterator.
872 /// [`Option`]: ../../std/option/enum.Option.html
879 /// let a = [1, 2, 3];
881 /// let mut iter = a.iter().scan(1, |state, &x| {
882 /// // each iteration, we'll multiply the state by the element
883 /// *state = *state * x;
885 /// // the value passed on to the next iteration
889 /// assert_eq!(iter.next(), Some(1));
890 /// assert_eq!(iter.next(), Some(2));
891 /// assert_eq!(iter.next(), Some(6));
892 /// assert_eq!(iter.next(), None);
895 #[stable(feature = "rust1", since = "1.0.0")]
896 fn scan
<St
, B
, F
>(self, initial_state
: St
, f
: F
) -> Scan
<Self, St
, F
>
897 where Self: Sized
, F
: FnMut(&mut St
, Self::Item
) -> Option
<B
>,
899 Scan{iter: self, f: f, state: initial_state}
902 /// Creates an iterator that works like map, but flattens nested structure.
904 /// The [`map()`] adapter is very useful, but only when the closure
905 /// argument produces values. If it produces an iterator instead, there's
906 /// an extra layer of indirection. `flat_map()` will remove this extra layer
909 /// [`map()`]: #method.map
911 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
912 /// one item for each element, and `flat_map()`'s closure returns an
913 /// iterator for each element.
920 /// let words = ["alpha", "beta", "gamma"];
922 /// // chars() returns an iterator
923 /// let merged: String = words.iter()
924 /// .flat_map(|s| s.chars())
926 /// assert_eq!(merged, "alphabetagamma");
929 #[stable(feature = "rust1", since = "1.0.0")]
930 fn flat_map
<U
, F
>(self, f
: F
) -> FlatMap
<Self, U
, F
>
931 where Self: Sized
, U
: IntoIterator
, F
: FnMut(Self::Item
) -> U
,
933 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
936 /// Creates an iterator which ends after the first `None`.
938 /// After an iterator returns `None`, future calls may or may not yield
939 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
940 /// `None` is given, it will always return `None` forever.
947 /// // an iterator which alternates between Some and None
948 /// struct Alternate {
952 /// impl Iterator for Alternate {
955 /// fn next(&mut self) -> Option<i32> {
956 /// let val = self.state;
957 /// self.state = self.state + 1;
959 /// // if it's even, Some(i32), else None
960 /// if val % 2 == 0 {
968 /// let mut iter = Alternate { state: 0 };
970 /// // we can see our iterator going back and forth
971 /// assert_eq!(iter.next(), Some(0));
972 /// assert_eq!(iter.next(), None);
973 /// assert_eq!(iter.next(), Some(2));
974 /// assert_eq!(iter.next(), None);
976 /// // however, once we fuse it...
977 /// let mut iter = iter.fuse();
979 /// assert_eq!(iter.next(), Some(4));
980 /// assert_eq!(iter.next(), None);
982 /// // it will always return None after the first time.
983 /// assert_eq!(iter.next(), None);
984 /// assert_eq!(iter.next(), None);
985 /// assert_eq!(iter.next(), None);
988 #[stable(feature = "rust1", since = "1.0.0")]
989 fn fuse(self) -> Fuse
<Self> where Self: Sized
{
990 Fuse{iter: self, done: false}
993 /// Do something with each element of an iterator, passing the value on.
995 /// When using iterators, you'll often chain several of them together.
996 /// While working on such code, you might want to check out what's
997 /// happening at various parts in the pipeline. To do that, insert
998 /// a call to `inspect()`.
1000 /// It's much more common for `inspect()` to be used as a debugging tool
1001 /// than to exist in your final code, but never say never.
1008 /// let a = [1, 4, 2, 3];
1010 /// // this iterator sequence is complex.
1011 /// let sum = a.iter()
1013 /// .filter(|&x| x % 2 == 0)
1014 /// .fold(0, |sum, i| sum + i);
1016 /// println!("{}", sum);
1018 /// // let's add some inspect() calls to investigate what's happening
1019 /// let sum = a.iter()
1021 /// .inspect(|x| println!("about to filter: {}", x))
1022 /// .filter(|&x| x % 2 == 0)
1023 /// .inspect(|x| println!("made it through filter: {}", x))
1024 /// .fold(0, |sum, i| sum + i);
1026 /// println!("{}", sum);
1029 /// This will print:
1032 /// about to filter: 1
1033 /// about to filter: 4
1034 /// made it through filter: 4
1035 /// about to filter: 2
1036 /// made it through filter: 2
1037 /// about to filter: 3
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 fn inspect
<F
>(self, f
: F
) -> Inspect
<Self, F
> where
1043 Self: Sized
, F
: FnMut(&Self::Item
),
1045 Inspect{iter: self, f: f}
1048 /// Borrows an iterator, rather than consuming it.
1050 /// This is useful to allow applying iterator adaptors while still
1051 /// retaining ownership of the original iterator.
1058 /// let a = [1, 2, 3];
1060 /// let iter = a.into_iter();
1062 /// let sum: i32 = iter.take(5)
1063 /// .fold(0, |acc, &i| acc + i );
1065 /// assert_eq!(sum, 6);
1067 /// // if we try to use iter again, it won't work. The following line
1068 /// // gives "error: use of moved value: `iter`
1069 /// // assert_eq!(iter.next(), None);
1071 /// // let's try that again
1072 /// let a = [1, 2, 3];
1074 /// let mut iter = a.into_iter();
1076 /// // instead, we add in a .by_ref()
1077 /// let sum: i32 = iter.by_ref()
1079 /// .fold(0, |acc, &i| acc + i );
1081 /// assert_eq!(sum, 3);
1083 /// // now this is just fine:
1084 /// assert_eq!(iter.next(), Some(&3));
1085 /// assert_eq!(iter.next(), None);
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1090 /// Transforms an iterator into a collection.
1092 /// `collect()` can take anything iterable, and turn it into a relevant
1093 /// collection. This is one of the more powerful methods in the standard
1094 /// library, used in a variety of contexts.
1096 /// The most basic pattern in which `collect()` is used is to turn one
1097 /// collection into another. You take a collection, call `iter()` on it,
1098 /// do a bunch of transformations, and then `collect()` at the end.
1100 /// One of the keys to `collect()`'s power is that many things you might
1101 /// not think of as 'collections' actually are. For example, a [`String`]
1102 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1103 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1106 /// [`String`]: ../../std/string/struct.String.html
1107 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1108 /// [`char`]: ../../std/primitive.char.html
1110 /// Because `collect()` is so general, it can cause problems with type
1111 /// inference. As such, `collect()` is one of the few times you'll see
1112 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1113 /// helps the inference algorithm understand specifically which collection
1114 /// you're trying to collect into.
1121 /// let a = [1, 2, 3];
1123 /// let doubled: Vec<i32> = a.iter()
1124 /// .map(|&x| x * 2)
1127 /// assert_eq!(vec![2, 4, 6], doubled);
1130 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1131 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1133 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1136 /// use std::collections::VecDeque;
1138 /// let a = [1, 2, 3];
1140 /// let doubled: VecDeque<i32> = a.iter()
1141 /// .map(|&x| x * 2)
1144 /// assert_eq!(2, doubled[0]);
1145 /// assert_eq!(4, doubled[1]);
1146 /// assert_eq!(6, doubled[2]);
1149 /// Using the 'turbofish' instead of annotating `doubled`:
1152 /// let a = [1, 2, 3];
1154 /// let doubled = a.iter()
1155 /// .map(|&x| x * 2)
1156 /// .collect::<Vec<i32>>();
1158 /// assert_eq!(vec![2, 4, 6], doubled);
1161 /// Because `collect()` cares about what you're collecting into, you can
1162 /// still use a partial type hint, `_`, with the turbofish:
1165 /// let a = [1, 2, 3];
1167 /// let doubled = a.iter()
1168 /// .map(|&x| x * 2)
1169 /// .collect::<Vec<_>>();
1171 /// assert_eq!(vec![2, 4, 6], doubled);
1174 /// Using `collect()` to make a [`String`]:
1177 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1179 /// let hello: String = chars.iter()
1180 /// .map(|&x| x as u8)
1181 /// .map(|x| (x + 1) as char)
1184 /// assert_eq!("hello", hello);
1187 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1188 /// see if any of them failed:
1191 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1193 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1195 /// // gives us the first error
1196 /// assert_eq!(Err("nope"), result);
1198 /// let results = [Ok(1), Ok(3)];
1200 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1202 /// // gives us the list of answers
1203 /// assert_eq!(Ok(vec![1, 3]), result);
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 fn collect
<B
: FromIterator
<Self::Item
>>(self) -> B
where Self: Sized
{
1208 FromIterator
::from_iter(self)
1211 /// Consumes an iterator, creating two collections from it.
1213 /// The predicate passed to `partition()` can return `true`, or `false`.
1214 /// `partition()` returns a pair, all of the elements for which it returned
1215 /// `true`, and all of the elements for which it returned `false`.
1222 /// let a = [1, 2, 3];
1224 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1225 /// .partition(|&n| n % 2 == 0);
1227 /// assert_eq!(even, vec![2]);
1228 /// assert_eq!(odd, vec![1, 3]);
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 fn partition
<B
, F
>(self, mut f
: F
) -> (B
, B
) where
1233 B
: Default
+ Extend
<Self::Item
>,
1234 F
: FnMut(&Self::Item
) -> bool
1236 let mut left
: B
= Default
::default();
1237 let mut right
: B
= Default
::default();
1241 left
.extend(Some(x
))
1243 right
.extend(Some(x
))
1250 /// An iterator adaptor that applies a function, producing a single, final value.
1252 /// `fold()` takes two arguments: an initial value, and a closure with two
1253 /// arguments: an 'accumulator', and an element. The closure returns the value that
1254 /// the accumulator should have for the next iteration.
1256 /// The initial value is the value the accumulator will have on the first
1259 /// After applying this closure to every element of the iterator, `fold()`
1260 /// returns the accumulator.
1262 /// This operation is sometimes called 'reduce' or 'inject'.
1264 /// Folding is useful whenever you have a collection of something, and want
1265 /// to produce a single value from it.
1272 /// let a = [1, 2, 3];
1274 /// // the sum of all of the elements of a
1275 /// let sum = a.iter()
1276 /// .fold(0, |acc, &x| acc + x);
1278 /// assert_eq!(sum, 6);
1281 /// Let's walk through each step of the iteration here:
1283 /// | element | acc | x | result |
1284 /// |---------|-----|---|--------|
1286 /// | 1 | 0 | 1 | 1 |
1287 /// | 2 | 1 | 2 | 3 |
1288 /// | 3 | 3 | 3 | 6 |
1290 /// And so, our final result, `6`.
1292 /// It's common for people who haven't used iterators a lot to
1293 /// use a `for` loop with a list of things to build up a result. Those
1294 /// can be turned into `fold()`s:
1297 /// let numbers = [1, 2, 3, 4, 5];
1299 /// let mut result = 0;
1302 /// for i in &numbers {
1303 /// result = result + i;
1307 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1309 /// // they're the same
1310 /// assert_eq!(result, result2);
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 fn fold
<B
, F
>(self, init
: B
, mut f
: F
) -> B
where
1315 Self: Sized
, F
: FnMut(B
, Self::Item
) -> B
,
1317 let mut accum
= init
;
1319 accum
= f(accum
, x
);
1324 /// Tests if every element of the iterator matches a predicate.
1326 /// `all()` takes a closure that returns `true` or `false`. It applies
1327 /// this closure to each element of the iterator, and if they all return
1328 /// `true`, then so does `all()`. If any of them return `false`, it
1329 /// returns `false`.
1331 /// `all()` is short-circuiting; in other words, it will stop processing
1332 /// as soon as it finds a `false`, given that no matter what else happens,
1333 /// the result will also be `false`.
1335 /// An empty iterator returns `true`.
1342 /// let a = [1, 2, 3];
1344 /// assert!(a.iter().all(|&x| x > 0));
1346 /// assert!(!a.iter().all(|&x| x > 2));
1349 /// Stopping at the first `false`:
1352 /// let a = [1, 2, 3];
1354 /// let mut iter = a.iter();
1356 /// assert!(!iter.all(|&x| x != 2));
1358 /// // we can still use `iter`, as there are more elements.
1359 /// assert_eq!(iter.next(), Some(&3));
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 fn all
<F
>(&mut self, mut f
: F
) -> bool
where
1364 Self: Sized
, F
: FnMut(Self::Item
) -> bool
1374 /// Tests if any element of the iterator matches a predicate.
1376 /// `any()` takes a closure that returns `true` or `false`. It applies
1377 /// this closure to each element of the iterator, and if any of them return
1378 /// `true`, then so does `any()`. If they all return `false`, it
1379 /// returns `false`.
1381 /// `any()` is short-circuiting; in other words, it will stop processing
1382 /// as soon as it finds a `true`, given that no matter what else happens,
1383 /// the result will also be `true`.
1385 /// An empty iterator returns `false`.
1392 /// let a = [1, 2, 3];
1394 /// assert!(a.iter().any(|&x| x > 0));
1396 /// assert!(!a.iter().any(|&x| x > 5));
1399 /// Stopping at the first `true`:
1402 /// let a = [1, 2, 3];
1404 /// let mut iter = a.iter();
1406 /// assert!(iter.any(|&x| x != 2));
1408 /// // we can still use `iter`, as there are more elements.
1409 /// assert_eq!(iter.next(), Some(&2));
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 fn any
<F
>(&mut self, mut f
: F
) -> bool
where
1415 F
: FnMut(Self::Item
) -> bool
1425 /// Searches for an element of an iterator that satisfies a predicate.
1427 /// `find()` takes a closure that returns `true` or `false`. It applies
1428 /// this closure to each element of the iterator, and if any of them return
1429 /// `true`, then `find()` returns `Some(element)`. If they all return
1430 /// `false`, it returns `None`.
1432 /// `find()` is short-circuiting; in other words, it will stop processing
1433 /// as soon as the closure returns `true`.
1435 /// Because `find()` takes a reference, and many iterators iterate over
1436 /// references, this leads to a possibly confusing situation where the
1437 /// argument is a double reference. You can see this effect in the
1438 /// examples below, with `&&x`.
1445 /// let a = [1, 2, 3];
1447 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1449 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1452 /// Stopping at the first `true`:
1455 /// let a = [1, 2, 3];
1457 /// let mut iter = a.iter();
1459 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1461 /// // we can still use `iter`, as there are more elements.
1462 /// assert_eq!(iter.next(), Some(&3));
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 fn find
<P
>(&mut self, mut predicate
: P
) -> Option
<Self::Item
> where
1468 P
: FnMut(&Self::Item
) -> bool
,
1471 if predicate(&x
) { return Some(x) }
1476 /// Searches for an element in an iterator, returning its index.
1478 /// `position()` takes a closure that returns `true` or `false`. It applies
1479 /// this closure to each element of the iterator, and if one of them
1480 /// returns `true`, then `position()` returns `Some(index)`. If all of
1481 /// them return `false`, it returns `None`.
1483 /// `position()` is short-circuiting; in other words, it will stop
1484 /// processing as soon as it finds a `true`.
1486 /// # Overflow Behavior
1488 /// The method does no guarding against overflows, so if there are more
1489 /// than `usize::MAX` non-matching elements, it either produces the wrong
1490 /// result or panics. If debug assertions are enabled, a panic is
1495 /// This function might panic if the iterator has more than `usize::MAX`
1496 /// non-matching elements.
1503 /// let a = [1, 2, 3];
1505 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1507 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1510 /// Stopping at the first `true`:
1513 /// let a = [1, 2, 3];
1515 /// let mut iter = a.iter();
1517 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1519 /// // we can still use `iter`, as there are more elements.
1520 /// assert_eq!(iter.next(), Some(&3));
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 fn position
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1526 P
: FnMut(Self::Item
) -> bool
,
1528 // `enumerate` might overflow.
1529 for (i
, x
) in self.enumerate() {
1537 /// Searches for an element in an iterator from the right, returning its
1540 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1541 /// this closure to each element of the iterator, starting from the end,
1542 /// and if one of them returns `true`, then `rposition()` returns
1543 /// `Some(index)`. If all of them return `false`, it returns `None`.
1545 /// `rposition()` is short-circuiting; in other words, it will stop
1546 /// processing as soon as it finds a `true`.
1553 /// let a = [1, 2, 3];
1555 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1557 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1560 /// Stopping at the first `true`:
1563 /// let a = [1, 2, 3];
1565 /// let mut iter = a.iter();
1567 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1569 /// // we can still use `iter`, as there are more elements.
1570 /// assert_eq!(iter.next(), Some(&1));
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 fn rposition
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1575 P
: FnMut(Self::Item
) -> bool
,
1576 Self: Sized
+ ExactSizeIterator
+ DoubleEndedIterator
1578 let mut i
= self.len();
1580 while let Some(v
) = self.next_back() {
1584 // No need for an overflow check here, because `ExactSizeIterator`
1585 // implies that the number of elements fits into a `usize`.
1591 /// Returns the maximum element of an iterator.
1593 /// If the two elements are equally maximum, the latest element is
1601 /// let a = [1, 2, 3];
1603 /// assert_eq!(a.iter().max(), Some(&3));
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 fn max(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1611 // switch to y even if it is only equal, to preserve
1613 |_
, x
, _
, y
| *x
<= *y
)
1617 /// Returns the minimum element of an iterator.
1619 /// If the two elements are equally minimum, the first element is
1627 /// let a = [1, 2, 3];
1629 /// assert_eq!(a.iter().min(), Some(&1));
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 fn min(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1637 // only switch to y if it is strictly smaller, to
1638 // preserve stability.
1639 |_
, x
, _
, y
| *x
> *y
)
1643 /// Returns the element that gives the maximum value from the
1644 /// specified function.
1646 /// Returns the rightmost element if the comparison determines two elements
1647 /// to be equally maximum.
1652 /// let a = [-3_i32, 0, 1, 5, -10];
1653 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1656 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1657 fn max_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1658 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1662 // switch to y even if it is only equal, to preserve
1664 |x_p
, _
, y_p
, _
| x_p
<= y_p
)
1668 /// Returns the element that gives the minimum value from the
1669 /// specified function.
1671 /// Returns the latest element if the comparison determines two elements
1672 /// to be equally minimum.
1677 /// let a = [-3_i32, 0, 1, 5, -10];
1678 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1680 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1681 fn min_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1682 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1686 // only switch to y if it is strictly smaller, to
1687 // preserve stability.
1688 |x_p
, _
, y_p
, _
| x_p
> y_p
)
1692 /// Reverses an iterator's direction.
1694 /// Usually, iterators iterate from left to right. After using `rev()`,
1695 /// an iterator will instead iterate from right to left.
1697 /// This is only possible if the iterator has an end, so `rev()` only
1698 /// works on [`DoubleEndedIterator`]s.
1700 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1705 /// let a = [1, 2, 3];
1707 /// let mut iter = a.iter().rev();
1709 /// assert_eq!(iter.next(), Some(&3));
1710 /// assert_eq!(iter.next(), Some(&2));
1711 /// assert_eq!(iter.next(), Some(&1));
1713 /// assert_eq!(iter.next(), None);
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 fn rev(self) -> Rev
<Self> where Self: Sized
+ DoubleEndedIterator
{
1721 /// Converts an iterator of pairs into a pair of containers.
1723 /// `unzip()` consumes an entire iterator of pairs, producing two
1724 /// collections: one from the left elements of the pairs, and one
1725 /// from the right elements.
1727 /// This function is, in some sense, the opposite of [`zip()`].
1729 /// [`zip()`]: #method.zip
1736 /// let a = [(1, 2), (3, 4)];
1738 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1740 /// assert_eq!(left, [1, 3]);
1741 /// assert_eq!(right, [2, 4]);
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 fn unzip
<A
, B
, FromA
, FromB
>(self) -> (FromA
, FromB
) where
1745 FromA
: Default
+ Extend
<A
>,
1746 FromB
: Default
+ Extend
<B
>,
1747 Self: Sized
+ Iterator
<Item
=(A
, B
)>,
1749 struct SizeHint
<A
>(usize, Option
<usize>, marker
::PhantomData
<A
>);
1750 impl<A
> Iterator
for SizeHint
<A
> {
1753 fn next(&mut self) -> Option
<A
> { None }
1754 fn size_hint(&self) -> (usize, Option
<usize>) {
1759 let (lo
, hi
) = self.size_hint();
1760 let mut ts
: FromA
= Default
::default();
1761 let mut us
: FromB
= Default
::default();
1763 ts
.extend(SizeHint(lo
, hi
, marker
::PhantomData
));
1764 us
.extend(SizeHint(lo
, hi
, marker
::PhantomData
));
1766 for (t
, u
) in self {
1774 /// Creates an iterator which `clone()`s all of its elements.
1776 /// This is useful when you have an iterator over `&T`, but you need an
1777 /// iterator over `T`.
1784 /// let a = [1, 2, 3];
1786 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1788 /// // cloned is the same as .map(|&x| x), for integers
1789 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1791 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1792 /// assert_eq!(v_map, vec![1, 2, 3]);
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 fn cloned
<'a
, T
: 'a
>(self) -> Cloned
<Self>
1796 where Self: Sized
+ Iterator
<Item
=&'a T
>, T
: Clone
1801 /// Repeats an iterator endlessly.
1803 /// Instead of stopping at `None`, the iterator will instead start again,
1804 /// from the beginning. After iterating again, it will start at the
1805 /// beginning again. And again. And again. Forever.
1812 /// let a = [1, 2, 3];
1814 /// let mut it = a.iter().cycle();
1816 /// assert_eq!(it.next(), Some(&1));
1817 /// assert_eq!(it.next(), Some(&2));
1818 /// assert_eq!(it.next(), Some(&3));
1819 /// assert_eq!(it.next(), Some(&1));
1820 /// assert_eq!(it.next(), Some(&2));
1821 /// assert_eq!(it.next(), Some(&3));
1822 /// assert_eq!(it.next(), Some(&1));
1824 #[stable(feature = "rust1", since = "1.0.0")]
1826 fn cycle(self) -> Cycle
<Self> where Self: Sized
+ Clone
{
1827 Cycle{orig: self.clone(), iter: self}
1830 /// Sums the elements of an iterator.
1832 /// Takes each element, adds them together, and returns the result.
1834 /// An empty iterator returns the zero value of the type.
1841 /// #![feature(iter_arith)]
1843 /// let a = [1, 2, 3];
1844 /// let sum: i32 = a.iter().sum();
1846 /// assert_eq!(sum, 6);
1848 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
1850 fn sum
<S
>(self) -> S
where
1851 S
: Add
<Self::Item
, Output
=S
> + Zero
,
1854 self.fold(Zero
::zero(), |s
, e
| s
+ e
)
1857 /// Iterates over the entire iterator, multiplying all the elements
1859 /// An empty iterator returns the one value of the type.
1864 /// #![feature(iter_arith)]
1866 /// fn factorial(n: u32) -> u32 {
1867 /// (1..).take_while(|&i| i <= n).product()
1869 /// assert_eq!(factorial(0), 1);
1870 /// assert_eq!(factorial(1), 1);
1871 /// assert_eq!(factorial(5), 120);
1873 #[unstable(feature="iter_arith", reason = "bounds recently changed",
1875 fn product
<P
>(self) -> P
where
1876 P
: Mul
<Self::Item
, Output
=P
> + One
,
1879 self.fold(One
::one(), |p
, e
| p
* e
)
1882 /// Lexicographically compares the elements of this `Iterator` with those
1884 #[stable(feature = "iter_order", since = "1.5.0")]
1885 fn cmp
<I
>(mut self, other
: I
) -> Ordering
where
1886 I
: IntoIterator
<Item
= Self::Item
>,
1890 let mut other
= other
.into_iter();
1893 match (self.next(), other
.next()) {
1894 (None
, None
) => return Ordering
::Equal
,
1895 (None
, _
) => return Ordering
::Less
,
1896 (_
, None
) => return Ordering
::Greater
,
1897 (Some(x
), Some(y
)) => match x
.cmp(&y
) {
1898 Ordering
::Equal
=> (),
1899 non_eq
=> return non_eq
,
1905 /// Lexicographically compares the elements of this `Iterator` with those
1907 #[stable(feature = "iter_order", since = "1.5.0")]
1908 fn partial_cmp
<I
>(mut self, other
: I
) -> Option
<Ordering
> where
1910 Self::Item
: PartialOrd
<I
::Item
>,
1913 let mut other
= other
.into_iter();
1916 match (self.next(), other
.next()) {
1917 (None
, None
) => return Some(Ordering
::Equal
),
1918 (None
, _
) => return Some(Ordering
::Less
),
1919 (_
, None
) => return Some(Ordering
::Greater
),
1920 (Some(x
), Some(y
)) => match x
.partial_cmp(&y
) {
1921 Some(Ordering
::Equal
) => (),
1922 non_eq
=> return non_eq
,
1928 /// Determines if the elements of this `Iterator` are equal to those of
1930 #[stable(feature = "iter_order", since = "1.5.0")]
1931 fn eq
<I
>(mut self, other
: I
) -> bool
where
1933 Self::Item
: PartialEq
<I
::Item
>,
1936 let mut other
= other
.into_iter();
1939 match (self.next(), other
.next()) {
1940 (None
, None
) => return true,
1941 (None
, _
) | (_
, None
) => return false,
1942 (Some(x
), Some(y
)) => if x
!= y { return false }
,
1947 /// Determines if the elements of this `Iterator` are unequal to those of
1949 #[stable(feature = "iter_order", since = "1.5.0")]
1950 fn ne
<I
>(mut self, other
: I
) -> bool
where
1952 Self::Item
: PartialEq
<I
::Item
>,
1955 let mut other
= other
.into_iter();
1958 match (self.next(), other
.next()) {
1959 (None
, None
) => return false,
1960 (None
, _
) | (_
, None
) => return true,
1961 (Some(x
), Some(y
)) => if x
.ne(&y
) { return true }
,
1966 /// Determines if the elements of this `Iterator` are lexicographically
1967 /// less than those of another.
1968 #[stable(feature = "iter_order", since = "1.5.0")]
1969 fn lt
<I
>(mut self, other
: I
) -> bool
where
1971 Self::Item
: PartialOrd
<I
::Item
>,
1974 let mut other
= other
.into_iter();
1977 match (self.next(), other
.next()) {
1978 (None
, None
) => return false,
1979 (None
, _
) => return true,
1980 (_
, None
) => return false,
1981 (Some(x
), Some(y
)) => {
1982 match x
.partial_cmp(&y
) {
1983 Some(Ordering
::Less
) => return true,
1984 Some(Ordering
::Equal
) => {}
1985 Some(Ordering
::Greater
) => return false,
1986 None
=> return false,
1993 /// Determines if the elements of this `Iterator` are lexicographically
1994 /// less or equal to those of another.
1995 #[stable(feature = "iter_order", since = "1.5.0")]
1996 fn le
<I
>(mut self, other
: I
) -> bool
where
1998 Self::Item
: PartialOrd
<I
::Item
>,
2001 let mut other
= other
.into_iter();
2004 match (self.next(), other
.next()) {
2005 (None
, None
) => return true,
2006 (None
, _
) => return true,
2007 (_
, None
) => return false,
2008 (Some(x
), Some(y
)) => {
2009 match x
.partial_cmp(&y
) {
2010 Some(Ordering
::Less
) => return true,
2011 Some(Ordering
::Equal
) => {}
2012 Some(Ordering
::Greater
) => return false,
2013 None
=> return false,
2020 /// Determines if the elements of this `Iterator` are lexicographically
2021 /// greater than those of another.
2022 #[stable(feature = "iter_order", since = "1.5.0")]
2023 fn gt
<I
>(mut self, other
: I
) -> bool
where
2025 Self::Item
: PartialOrd
<I
::Item
>,
2028 let mut other
= other
.into_iter();
2031 match (self.next(), other
.next()) {
2032 (None
, None
) => return false,
2033 (None
, _
) => return false,
2034 (_
, None
) => return true,
2035 (Some(x
), Some(y
)) => {
2036 match x
.partial_cmp(&y
) {
2037 Some(Ordering
::Less
) => return false,
2038 Some(Ordering
::Equal
) => {}
2039 Some(Ordering
::Greater
) => return true,
2040 None
=> return false,
2047 /// Determines if the elements of this `Iterator` are lexicographically
2048 /// greater than or equal to those of another.
2049 #[stable(feature = "iter_order", since = "1.5.0")]
2050 fn ge
<I
>(mut self, other
: I
) -> bool
where
2052 Self::Item
: PartialOrd
<I
::Item
>,
2055 let mut other
= other
.into_iter();
2058 match (self.next(), other
.next()) {
2059 (None
, None
) => return true,
2060 (None
, _
) => return false,
2061 (_
, None
) => return true,
2062 (Some(x
), Some(y
)) => {
2063 match x
.partial_cmp(&y
) {
2064 Some(Ordering
::Less
) => return false,
2065 Some(Ordering
::Equal
) => {}
2066 Some(Ordering
::Greater
) => return true,
2067 None
=> return false,
2075 /// Select an element from an iterator based on the given projection
2076 /// and "comparison" function.
2078 /// This is an idiosyncratic helper to try to factor out the
2079 /// commonalities of {max,min}{,_by}. In particular, this avoids
2080 /// having to implement optimizations several times.
2082 fn select_fold1
<I
,B
, FProj
, FCmp
>(mut it
: I
,
2084 mut f_cmp
: FCmp
) -> Option
<(B
, I
::Item
)>
2086 FProj
: FnMut(&I
::Item
) -> B
,
2087 FCmp
: FnMut(&B
, &I
::Item
, &B
, &I
::Item
) -> bool
2089 // start with the first element as our selection. This avoids
2090 // having to use `Option`s inside the loop, translating to a
2091 // sizeable performance gain (6x in one case).
2092 it
.next().map(|mut sel
| {
2093 let mut sel_p
= f_proj(&sel
);
2096 let x_p
= f_proj(&x
);
2097 if f_cmp(&sel_p
, &sel
, &x_p
, &x
) {
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<'a
, I
: Iterator
+ ?Sized
> Iterator
for &'a
mut I
{
2108 type Item
= I
::Item
;
2109 fn next(&mut self) -> Option
<I
::Item
> { (**self).next() }
2110 fn size_hint(&self) -> (usize, Option
<usize>) { (**self).size_hint() }