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.
13 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse};
14 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev};
15 use super::{Zip, Sum, Product};
16 use super::{ChainState, FromIterator, ZipImpl};
18 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
20 /// An interface for dealing with iterators.
22 /// This is the main iterator trait. For more about the concept of iterators
23 /// generally, please see the [module-level documentation]. In particular, you
24 /// may want to know how to [implement `Iterator`][impl].
26 /// [module-level documentation]: index.html
27 /// [impl]: index.html#implementing-iterator
28 #[stable(feature = "rust1", since = "1.0.0")]
29 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
30 `.iter()` or a similar method"]
32 /// The type of the elements being iterated over.
33 #[stable(feature = "rust1", since = "1.0.0")]
36 /// Advances the iterator and returns the next value.
38 /// Returns `None` when iteration is finished. Individual iterator
39 /// implementations may choose to resume iteration, and so calling `next()`
40 /// again may or may not eventually start returning `Some(Item)` again at some
48 /// let a = [1, 2, 3];
50 /// let mut iter = a.iter();
52 /// // A call to next() returns the next value...
53 /// assert_eq!(Some(&1), iter.next());
54 /// assert_eq!(Some(&2), iter.next());
55 /// assert_eq!(Some(&3), iter.next());
57 /// // ... and then None once it's over.
58 /// assert_eq!(None, iter.next());
60 /// // More calls may or may not return None. Here, they always will.
61 /// assert_eq!(None, iter.next());
62 /// assert_eq!(None, iter.next());
64 #[stable(feature = "rust1", since = "1.0.0")]
65 fn next(&mut self) -> Option<Self::Item>;
67 /// Returns the bounds on the remaining length of the iterator.
69 /// Specifically, `size_hint()` returns a tuple where the first element
70 /// is the lower bound, and the second element is the upper bound.
72 /// The second half of the tuple that is returned is an `Option<usize>`. A
73 /// `None` here means that either there is no known upper bound, or the
74 /// upper bound is larger than `usize`.
76 /// # Implementation notes
78 /// It is not enforced that an iterator implementation yields the declared
79 /// number of elements. A buggy iterator may yield less than the lower bound
80 /// or more than the upper bound of elements.
82 /// `size_hint()` is primarily intended to be used for optimizations such as
83 /// reserving space for the elements of the iterator, but must not be
84 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
85 /// implementation of `size_hint()` should not lead to memory safety
88 /// That said, the implementation should provide a correct estimation,
89 /// because otherwise it would be a violation of the trait's protocol.
91 /// The default implementation returns `(0, None)` which is correct for any
99 /// let a = [1, 2, 3];
100 /// let iter = a.iter();
102 /// assert_eq!((3, Some(3)), iter.size_hint());
105 /// A more complex example:
108 /// // The even numbers from zero to ten.
109 /// let iter = (0..10).filter(|x| x % 2 == 0);
111 /// // We might iterate from zero to ten times. Knowing that it's five
112 /// // exactly wouldn't be possible without executing filter().
113 /// assert_eq!((0, Some(10)), iter.size_hint());
115 /// // Let's add one five more numbers with chain()
116 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
118 /// // now both bounds are increased by five
119 /// assert_eq!((5, Some(15)), iter.size_hint());
122 /// Returning `None` for an upper bound:
125 /// // an infinite iterator has no upper bound
128 /// assert_eq!((0, None), iter.size_hint());
131 #[stable(feature = "rust1", since = "1.0.0")]
132 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
134 /// Consumes the iterator, counting the number of iterations and returning it.
136 /// This method will evaluate the iterator until its [`next()`] returns
137 /// `None`. Once `None` is encountered, `count()` returns the number of
138 /// times it called [`next()`].
140 /// [`next()`]: #tymethod.next
142 /// # Overflow Behavior
144 /// The method does no guarding against overflows, so counting elements of
145 /// an iterator with more than `usize::MAX` elements either produces the
146 /// wrong result or panics. If debug assertions are enabled, a panic is
151 /// This function might panic if the iterator has more than `usize::MAX`
159 /// let a = [1, 2, 3];
160 /// assert_eq!(a.iter().count(), 3);
162 /// let a = [1, 2, 3, 4, 5];
163 /// assert_eq!(a.iter().count(), 5);
166 #[rustc_inherit_overflow_checks]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 fn count(self) -> usize where Self: Sized {
170 self.fold(0, |cnt, _| cnt + 1)
173 /// Consumes the iterator, returning the last element.
175 /// This method will evaluate the iterator until it returns `None`. While
176 /// doing so, it keeps track of the current element. After `None` is
177 /// returned, `last()` will then return the last element it saw.
184 /// let a = [1, 2, 3];
185 /// assert_eq!(a.iter().last(), Some(&3));
187 /// let a = [1, 2, 3, 4, 5];
188 /// assert_eq!(a.iter().last(), Some(&5));
191 #[stable(feature = "rust1", since = "1.0.0")]
192 fn last(self) -> Option<Self::Item> where Self: Sized {
194 for x in self { last = Some(x); }
198 /// Consumes the `n` first elements of the iterator, then returns the
201 /// This method will evaluate the iterator `n` times, discarding those elements.
202 /// After it does so, it will call [`next()`] and return its value.
204 /// [`next()`]: #tymethod.next
206 /// Like most indexing operations, the count starts from zero, so `nth(0)`
207 /// returns the first value, `nth(1)` the second, and so on.
209 /// `nth()` will return `None` if `n` is greater than or equal to the length of the
217 /// let a = [1, 2, 3];
218 /// assert_eq!(a.iter().nth(1), Some(&2));
221 /// Calling `nth()` multiple times doesn't rewind the iterator:
224 /// let a = [1, 2, 3];
226 /// let mut iter = a.iter();
228 /// assert_eq!(iter.nth(1), Some(&2));
229 /// assert_eq!(iter.nth(1), None);
232 /// Returning `None` if there are less than `n + 1` elements:
235 /// let a = [1, 2, 3];
236 /// assert_eq!(a.iter().nth(10), None);
239 #[stable(feature = "rust1", since = "1.0.0")]
240 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
242 if n == 0 { return Some(x) }
248 /// Takes two iterators and creates a new iterator over both in sequence.
250 /// `chain()` will return a new iterator which will first iterate over
251 /// values from the first iterator and then over values from the second
254 /// In other words, it links two iterators together, in a chain. 🔗
261 /// let a1 = [1, 2, 3];
262 /// let a2 = [4, 5, 6];
264 /// let mut iter = a1.iter().chain(a2.iter());
266 /// assert_eq!(iter.next(), Some(&1));
267 /// assert_eq!(iter.next(), Some(&2));
268 /// assert_eq!(iter.next(), Some(&3));
269 /// assert_eq!(iter.next(), Some(&4));
270 /// assert_eq!(iter.next(), Some(&5));
271 /// assert_eq!(iter.next(), Some(&6));
272 /// assert_eq!(iter.next(), None);
275 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
276 /// anything that can be converted into an [`Iterator`], not just an
277 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
278 /// [`IntoIterator`], and so can be passed to `chain()` directly:
280 /// [`IntoIterator`]: trait.IntoIterator.html
281 /// [`Iterator`]: trait.Iterator.html
284 /// let s1 = &[1, 2, 3];
285 /// let s2 = &[4, 5, 6];
287 /// let mut iter = s1.iter().chain(s2);
289 /// assert_eq!(iter.next(), Some(&1));
290 /// assert_eq!(iter.next(), Some(&2));
291 /// assert_eq!(iter.next(), Some(&3));
292 /// assert_eq!(iter.next(), Some(&4));
293 /// assert_eq!(iter.next(), Some(&5));
294 /// assert_eq!(iter.next(), Some(&6));
295 /// assert_eq!(iter.next(), None);
298 #[stable(feature = "rust1", since = "1.0.0")]
299 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
300 Self: Sized, U: IntoIterator<Item=Self::Item>,
302 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
305 /// 'Zips up' two iterators into a single iterator of pairs.
307 /// `zip()` returns a new iterator that will iterate over two other
308 /// iterators, returning a tuple where the first element comes from the
309 /// first iterator, and the second element comes from the second iterator.
311 /// In other words, it zips two iterators together, into a single one.
313 /// When either iterator returns `None`, all further calls to `next()`
314 /// will return `None`.
321 /// let a1 = [1, 2, 3];
322 /// let a2 = [4, 5, 6];
324 /// let mut iter = a1.iter().zip(a2.iter());
326 /// assert_eq!(iter.next(), Some((&1, &4)));
327 /// assert_eq!(iter.next(), Some((&2, &5)));
328 /// assert_eq!(iter.next(), Some((&3, &6)));
329 /// assert_eq!(iter.next(), None);
332 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
333 /// anything that can be converted into an [`Iterator`], not just an
334 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
335 /// [`IntoIterator`], and so can be passed to `zip()` directly:
337 /// [`IntoIterator`]: trait.IntoIterator.html
338 /// [`Iterator`]: trait.Iterator.html
341 /// let s1 = &[1, 2, 3];
342 /// let s2 = &[4, 5, 6];
344 /// let mut iter = s1.iter().zip(s2);
346 /// assert_eq!(iter.next(), Some((&1, &4)));
347 /// assert_eq!(iter.next(), Some((&2, &5)));
348 /// assert_eq!(iter.next(), Some((&3, &6)));
349 /// assert_eq!(iter.next(), None);
352 /// `zip()` is often used to zip an infinite iterator to a finite one.
353 /// This works because the finite iterator will eventually return `None`,
354 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
357 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
359 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
361 /// assert_eq!((0, 'f'), enumerate[0]);
362 /// assert_eq!((0, 'f'), zipper[0]);
364 /// assert_eq!((1, 'o'), enumerate[1]);
365 /// assert_eq!((1, 'o'), zipper[1]);
367 /// assert_eq!((2, 'o'), enumerate[2]);
368 /// assert_eq!((2, 'o'), zipper[2]);
371 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
373 #[stable(feature = "rust1", since = "1.0.0")]
374 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
375 Self: Sized, U: IntoIterator
377 Zip::new(self, other.into_iter())
380 /// Takes a closure and creates an iterator which calls that closure on each
383 /// `map()` transforms one iterator into another, by means of its argument:
384 /// something that implements `FnMut`. It produces a new iterator which
385 /// calls this closure on each element of the original iterator.
387 /// If you are good at thinking in types, you can think of `map()` like this:
388 /// If you have an iterator that gives you elements of some type `A`, and
389 /// you want an iterator of some other type `B`, you can use `map()`,
390 /// passing a closure that takes an `A` and returns a `B`.
392 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
393 /// lazy, it is best used when you're already working with other iterators.
394 /// If you're doing some sort of looping for a side effect, it's considered
395 /// more idiomatic to use [`for`] than `map()`.
397 /// [`for`]: ../../book/loops.html#for
404 /// let a = [1, 2, 3];
406 /// let mut iter = a.into_iter().map(|x| 2 * x);
408 /// assert_eq!(iter.next(), Some(2));
409 /// assert_eq!(iter.next(), Some(4));
410 /// assert_eq!(iter.next(), Some(6));
411 /// assert_eq!(iter.next(), None);
414 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
417 /// # #![allow(unused_must_use)]
418 /// // don't do this:
419 /// (0..5).map(|x| println!("{}", x));
421 /// // it won't even execute, as it is lazy. Rust will warn you about this.
423 /// // Instead, use for:
425 /// println!("{}", x);
429 #[stable(feature = "rust1", since = "1.0.0")]
430 fn map<B, F>(self, f: F) -> Map<Self, F> where
431 Self: Sized, F: FnMut(Self::Item) -> B,
433 Map{iter: self, f: f}
436 /// Creates an iterator which uses a closure to determine if an element
437 /// should be yielded.
439 /// The closure must return `true` or `false`. `filter()` creates an
440 /// iterator which calls this closure on each element. If the closure
441 /// returns `true`, then the element is returned. If the closure returns
442 /// `false`, it will try again, and call the closure on the next element,
443 /// seeing if it passes the test.
450 /// let a = [0i32, 1, 2];
452 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
454 /// assert_eq!(iter.next(), Some(&1));
455 /// assert_eq!(iter.next(), Some(&2));
456 /// assert_eq!(iter.next(), None);
459 /// Because the closure passed to `filter()` takes a reference, and many
460 /// iterators iterate over references, this leads to a possibly confusing
461 /// situation, where the type of the closure is a double reference:
464 /// let a = [0, 1, 2];
466 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
468 /// assert_eq!(iter.next(), Some(&2));
469 /// assert_eq!(iter.next(), None);
472 /// It's common to instead use destructuring on the argument to strip away
476 /// let a = [0, 1, 2];
478 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
480 /// assert_eq!(iter.next(), Some(&2));
481 /// assert_eq!(iter.next(), None);
487 /// let a = [0, 1, 2];
489 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
491 /// assert_eq!(iter.next(), Some(&2));
492 /// assert_eq!(iter.next(), None);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
499 Self: Sized, P: FnMut(&Self::Item) -> bool,
501 Filter{iter: self, predicate: predicate}
504 /// Creates an iterator that both filters and maps.
506 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
507 /// iterator which calls this closure on each element. If the closure
508 /// returns `Some(element)`, then that element is returned. If the
509 /// closure returns `None`, it will try again, and call the closure on the
510 /// next element, seeing if it will return `Some`.
512 /// [`Option<T>`]: ../../std/option/enum.Option.html
514 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
517 /// [`filter()`]: #method.filter
518 /// [`map()`]: #method.map
520 /// > If the closure returns `Some(element)`, then that element is returned.
522 /// In other words, it removes the [`Option<T>`] layer automatically. If your
523 /// mapping is already returning an [`Option<T>`] and you want to skip over
524 /// `None`s, then `filter_map()` is much, much nicer to use.
531 /// let a = ["1", "2", "lol"];
533 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
535 /// assert_eq!(iter.next(), Some(1));
536 /// assert_eq!(iter.next(), Some(2));
537 /// assert_eq!(iter.next(), None);
540 /// Here's the same example, but with [`filter()`] and [`map()`]:
543 /// let a = ["1", "2", "lol"];
545 /// let mut iter = a.iter()
546 /// .map(|s| s.parse().ok())
547 /// .filter(|s| s.is_some());
549 /// assert_eq!(iter.next(), Some(Some(1)));
550 /// assert_eq!(iter.next(), Some(Some(2)));
551 /// assert_eq!(iter.next(), None);
554 /// There's an extra layer of `Some` in there.
556 #[stable(feature = "rust1", since = "1.0.0")]
557 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
558 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
560 FilterMap { iter: self, f: f }
563 /// Creates an iterator which gives the current iteration count as well as
566 /// The iterator returned yields pairs `(i, val)`, where `i` is the
567 /// current index of iteration and `val` is the value returned by the
570 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
571 /// different sized integer, the [`zip()`] function provides similar
574 /// [`usize`]: ../../std/primitive.usize.html
575 /// [`zip()`]: #method.zip
577 /// # Overflow Behavior
579 /// The method does no guarding against overflows, so enumerating more than
580 /// [`usize::MAX`] elements either produces the wrong result or panics. If
581 /// debug assertions are enabled, a panic is guaranteed.
583 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
587 /// The returned iterator might panic if the to-be-returned index would
588 /// overflow a `usize`.
593 /// let a = ['a', 'b', 'c'];
595 /// let mut iter = a.iter().enumerate();
597 /// assert_eq!(iter.next(), Some((0, &'a')));
598 /// assert_eq!(iter.next(), Some((1, &'b')));
599 /// assert_eq!(iter.next(), Some((2, &'c')));
600 /// assert_eq!(iter.next(), None);
603 #[stable(feature = "rust1", since = "1.0.0")]
604 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
605 Enumerate { iter: self, count: 0 }
608 /// Creates an iterator which can use `peek` to look at the next element of
609 /// the iterator without consuming it.
611 /// Adds a [`peek()`] method to an iterator. See its documentation for
612 /// more information.
614 /// Note that the underlying iterator is still advanced when `peek` is
615 /// called for the first time: In order to retrieve the next element,
616 /// `next` is called on the underlying iterator, hence any side effects of
617 /// the `next` method will occur.
619 /// [`peek()`]: struct.Peekable.html#method.peek
626 /// let xs = [1, 2, 3];
628 /// let mut iter = xs.iter().peekable();
630 /// // peek() lets us see into the future
631 /// assert_eq!(iter.peek(), Some(&&1));
632 /// assert_eq!(iter.next(), Some(&1));
634 /// assert_eq!(iter.next(), Some(&2));
636 /// // we can peek() multiple times, the iterator won't advance
637 /// assert_eq!(iter.peek(), Some(&&3));
638 /// assert_eq!(iter.peek(), Some(&&3));
640 /// assert_eq!(iter.next(), Some(&3));
642 /// // after the iterator is finished, so is peek()
643 /// assert_eq!(iter.peek(), None);
644 /// assert_eq!(iter.next(), None);
647 #[stable(feature = "rust1", since = "1.0.0")]
648 fn peekable(self) -> Peekable<Self> where Self: Sized {
649 Peekable{iter: self, peeked: None}
652 /// Creates an iterator that [`skip()`]s elements based on a predicate.
654 /// [`skip()`]: #method.skip
656 /// `skip_while()` takes a closure as an argument. It will call this
657 /// closure on each element of the iterator, and ignore elements
658 /// until it returns `false`.
660 /// After `false` is returned, `skip_while()`'s job is over, and the
661 /// rest of the elements are yielded.
668 /// let a = [-1i32, 0, 1];
670 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
672 /// assert_eq!(iter.next(), Some(&0));
673 /// assert_eq!(iter.next(), Some(&1));
674 /// assert_eq!(iter.next(), None);
677 /// Because the closure passed to `skip_while()` takes a reference, and many
678 /// iterators iterate over references, this leads to a possibly confusing
679 /// situation, where the type of the closure is a double reference:
682 /// let a = [-1, 0, 1];
684 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
686 /// assert_eq!(iter.next(), Some(&0));
687 /// assert_eq!(iter.next(), Some(&1));
688 /// assert_eq!(iter.next(), None);
691 /// Stopping after an initial `false`:
694 /// let a = [-1, 0, 1, -2];
696 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
698 /// assert_eq!(iter.next(), Some(&0));
699 /// assert_eq!(iter.next(), Some(&1));
701 /// // while this would have been false, since we already got a false,
702 /// // skip_while() isn't used any more
703 /// assert_eq!(iter.next(), Some(&-2));
705 /// assert_eq!(iter.next(), None);
708 #[stable(feature = "rust1", since = "1.0.0")]
709 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
710 Self: Sized, P: FnMut(&Self::Item) -> bool,
712 SkipWhile{iter: self, flag: false, predicate: predicate}
715 /// Creates an iterator that yields elements based on a predicate.
717 /// `take_while()` takes a closure as an argument. It will call this
718 /// closure on each element of the iterator, and yield elements
719 /// while it returns `true`.
721 /// After `false` is returned, `take_while()`'s job is over, and the
722 /// rest of the elements are ignored.
729 /// let a = [-1i32, 0, 1];
731 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
733 /// assert_eq!(iter.next(), Some(&-1));
734 /// assert_eq!(iter.next(), None);
737 /// Because the closure passed to `take_while()` takes a reference, and many
738 /// iterators iterate over references, this leads to a possibly confusing
739 /// situation, where the type of the closure is a double reference:
742 /// let a = [-1, 0, 1];
744 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
746 /// assert_eq!(iter.next(), Some(&-1));
747 /// assert_eq!(iter.next(), None);
750 /// Stopping after an initial `false`:
753 /// let a = [-1, 0, 1, -2];
755 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
757 /// assert_eq!(iter.next(), Some(&-1));
759 /// // We have more elements that are less than zero, but since we already
760 /// // got a false, take_while() isn't used any more
761 /// assert_eq!(iter.next(), None);
764 /// Because `take_while()` needs to look at the value in order to see if it
765 /// should be included or not, consuming iterators will see that it is
769 /// let a = [1, 2, 3, 4];
770 /// let mut iter = a.into_iter();
772 /// let result: Vec<i32> = iter.by_ref()
773 /// .take_while(|n| **n != 3)
777 /// assert_eq!(result, &[1, 2]);
779 /// let result: Vec<i32> = iter.cloned().collect();
781 /// assert_eq!(result, &[4]);
784 /// The `3` is no longer there, because it was consumed in order to see if
785 /// the iteration should stop, but wasn't placed back into the iterator or
786 /// some similar thing.
788 #[stable(feature = "rust1", since = "1.0.0")]
789 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
790 Self: Sized, P: FnMut(&Self::Item) -> bool,
792 TakeWhile{iter: self, flag: false, predicate: predicate}
795 /// Creates an iterator that skips the first `n` elements.
797 /// After they have been consumed, the rest of the elements are yielded.
804 /// let a = [1, 2, 3];
806 /// let mut iter = a.iter().skip(2);
808 /// assert_eq!(iter.next(), Some(&3));
809 /// assert_eq!(iter.next(), None);
812 #[stable(feature = "rust1", since = "1.0.0")]
813 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
814 Skip{iter: self, n: n}
817 /// Creates an iterator that yields its first `n` elements.
824 /// let a = [1, 2, 3];
826 /// let mut iter = a.iter().take(2);
828 /// assert_eq!(iter.next(), Some(&1));
829 /// assert_eq!(iter.next(), Some(&2));
830 /// assert_eq!(iter.next(), None);
833 /// `take()` is often used with an infinite iterator, to make it finite:
836 /// let mut iter = (0..).take(3);
838 /// assert_eq!(iter.next(), Some(0));
839 /// assert_eq!(iter.next(), Some(1));
840 /// assert_eq!(iter.next(), Some(2));
841 /// assert_eq!(iter.next(), None);
844 #[stable(feature = "rust1", since = "1.0.0")]
845 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
846 Take{iter: self, n: n}
849 /// An iterator adaptor similar to [`fold()`] that holds internal state and
850 /// produces a new iterator.
852 /// [`fold()`]: #method.fold
854 /// `scan()` takes two arguments: an initial value which seeds the internal
855 /// state, and a closure with two arguments, the first being a mutable
856 /// reference to the internal state and the second an iterator element.
857 /// The closure can assign to the internal state to share state between
860 /// On iteration, the closure will be applied to each element of the
861 /// iterator and the return value from the closure, an [`Option`], is
862 /// yielded by the iterator.
864 /// [`Option`]: ../../std/option/enum.Option.html
871 /// let a = [1, 2, 3];
873 /// let mut iter = a.iter().scan(1, |state, &x| {
874 /// // each iteration, we'll multiply the state by the element
875 /// *state = *state * x;
877 /// // the value passed on to the next iteration
881 /// assert_eq!(iter.next(), Some(1));
882 /// assert_eq!(iter.next(), Some(2));
883 /// assert_eq!(iter.next(), Some(6));
884 /// assert_eq!(iter.next(), None);
887 #[stable(feature = "rust1", since = "1.0.0")]
888 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
889 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
891 Scan{iter: self, f: f, state: initial_state}
894 /// Creates an iterator that works like map, but flattens nested structure.
896 /// The [`map()`] adapter is very useful, but only when the closure
897 /// argument produces values. If it produces an iterator instead, there's
898 /// an extra layer of indirection. `flat_map()` will remove this extra layer
901 /// [`map()`]: #method.map
903 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
904 /// one item for each element, and `flat_map()`'s closure returns an
905 /// iterator for each element.
912 /// let words = ["alpha", "beta", "gamma"];
914 /// // chars() returns an iterator
915 /// let merged: String = words.iter()
916 /// .flat_map(|s| s.chars())
918 /// assert_eq!(merged, "alphabetagamma");
921 #[stable(feature = "rust1", since = "1.0.0")]
922 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
923 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
925 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
928 /// Creates an iterator which ends after the first `None`.
930 /// After an iterator returns `None`, future calls may or may not yield
931 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
932 /// `None` is given, it will always return `None` forever.
939 /// // an iterator which alternates between Some and None
940 /// struct Alternate {
944 /// impl Iterator for Alternate {
947 /// fn next(&mut self) -> Option<i32> {
948 /// let val = self.state;
949 /// self.state = self.state + 1;
951 /// // if it's even, Some(i32), else None
952 /// if val % 2 == 0 {
960 /// let mut iter = Alternate { state: 0 };
962 /// // we can see our iterator going back and forth
963 /// assert_eq!(iter.next(), Some(0));
964 /// assert_eq!(iter.next(), None);
965 /// assert_eq!(iter.next(), Some(2));
966 /// assert_eq!(iter.next(), None);
968 /// // however, once we fuse it...
969 /// let mut iter = iter.fuse();
971 /// assert_eq!(iter.next(), Some(4));
972 /// assert_eq!(iter.next(), None);
974 /// // it will always return None after the first time.
975 /// assert_eq!(iter.next(), None);
976 /// assert_eq!(iter.next(), None);
977 /// assert_eq!(iter.next(), None);
980 #[stable(feature = "rust1", since = "1.0.0")]
981 fn fuse(self) -> Fuse<Self> where Self: Sized {
982 Fuse{iter: self, done: false}
985 /// Do something with each element of an iterator, passing the value on.
987 /// When using iterators, you'll often chain several of them together.
988 /// While working on such code, you might want to check out what's
989 /// happening at various parts in the pipeline. To do that, insert
990 /// a call to `inspect()`.
992 /// It's much more common for `inspect()` to be used as a debugging tool
993 /// than to exist in your final code, but never say never.
1000 /// let a = [1, 4, 2, 3];
1002 /// // this iterator sequence is complex.
1003 /// let sum = a.iter()
1005 /// .filter(|&x| x % 2 == 0)
1006 /// .fold(0, |sum, i| sum + i);
1008 /// println!("{}", sum);
1010 /// // let's add some inspect() calls to investigate what's happening
1011 /// let sum = a.iter()
1013 /// .inspect(|x| println!("about to filter: {}", x))
1014 /// .filter(|&x| x % 2 == 0)
1015 /// .inspect(|x| println!("made it through filter: {}", x))
1016 /// .fold(0, |sum, i| sum + i);
1018 /// println!("{}", sum);
1021 /// This will print:
1024 /// about to filter: 1
1025 /// about to filter: 4
1026 /// made it through filter: 4
1027 /// about to filter: 2
1028 /// made it through filter: 2
1029 /// about to filter: 3
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1035 Self: Sized, F: FnMut(&Self::Item),
1037 Inspect{iter: self, f: f}
1040 /// Borrows an iterator, rather than consuming it.
1042 /// This is useful to allow applying iterator adaptors while still
1043 /// retaining ownership of the original iterator.
1050 /// let a = [1, 2, 3];
1052 /// let iter = a.into_iter();
1054 /// let sum: i32 = iter.take(5)
1055 /// .fold(0, |acc, &i| acc + i );
1057 /// assert_eq!(sum, 6);
1059 /// // if we try to use iter again, it won't work. The following line
1060 /// // gives "error: use of moved value: `iter`
1061 /// // assert_eq!(iter.next(), None);
1063 /// // let's try that again
1064 /// let a = [1, 2, 3];
1066 /// let mut iter = a.into_iter();
1068 /// // instead, we add in a .by_ref()
1069 /// let sum: i32 = iter.by_ref()
1071 /// .fold(0, |acc, &i| acc + i );
1073 /// assert_eq!(sum, 3);
1075 /// // now this is just fine:
1076 /// assert_eq!(iter.next(), Some(&3));
1077 /// assert_eq!(iter.next(), None);
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1082 /// Transforms an iterator into a collection.
1084 /// `collect()` can take anything iterable, and turn it into a relevant
1085 /// collection. This is one of the more powerful methods in the standard
1086 /// library, used in a variety of contexts.
1088 /// The most basic pattern in which `collect()` is used is to turn one
1089 /// collection into another. You take a collection, call `iter()` on it,
1090 /// do a bunch of transformations, and then `collect()` at the end.
1092 /// One of the keys to `collect()`'s power is that many things you might
1093 /// not think of as 'collections' actually are. For example, a [`String`]
1094 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1095 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1098 /// [`String`]: ../../std/string/struct.String.html
1099 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1100 /// [`char`]: ../../std/primitive.char.html
1102 /// Because `collect()` is so general, it can cause problems with type
1103 /// inference. As such, `collect()` is one of the few times you'll see
1104 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1105 /// helps the inference algorithm understand specifically which collection
1106 /// you're trying to collect into.
1113 /// let a = [1, 2, 3];
1115 /// let doubled: Vec<i32> = a.iter()
1116 /// .map(|&x| x * 2)
1119 /// assert_eq!(vec![2, 4, 6], doubled);
1122 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1123 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1125 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1128 /// use std::collections::VecDeque;
1130 /// let a = [1, 2, 3];
1132 /// let doubled: VecDeque<i32> = a.iter()
1133 /// .map(|&x| x * 2)
1136 /// assert_eq!(2, doubled[0]);
1137 /// assert_eq!(4, doubled[1]);
1138 /// assert_eq!(6, doubled[2]);
1141 /// Using the 'turbofish' instead of annotating `doubled`:
1144 /// let a = [1, 2, 3];
1146 /// let doubled = a.iter()
1147 /// .map(|&x| x * 2)
1148 /// .collect::<Vec<i32>>();
1150 /// assert_eq!(vec![2, 4, 6], doubled);
1153 /// Because `collect()` cares about what you're collecting into, you can
1154 /// still use a partial type hint, `_`, with the turbofish:
1157 /// let a = [1, 2, 3];
1159 /// let doubled = a.iter()
1160 /// .map(|&x| x * 2)
1161 /// .collect::<Vec<_>>();
1163 /// assert_eq!(vec![2, 4, 6], doubled);
1166 /// Using `collect()` to make a [`String`]:
1169 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1171 /// let hello: String = chars.iter()
1172 /// .map(|&x| x as u8)
1173 /// .map(|x| (x + 1) as char)
1176 /// assert_eq!("hello", hello);
1179 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1180 /// see if any of them failed:
1183 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1185 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1187 /// // gives us the first error
1188 /// assert_eq!(Err("nope"), result);
1190 /// let results = [Ok(1), Ok(3)];
1192 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1194 /// // gives us the list of answers
1195 /// assert_eq!(Ok(vec![1, 3]), result);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1200 FromIterator::from_iter(self)
1203 /// Consumes an iterator, creating two collections from it.
1205 /// The predicate passed to `partition()` can return `true`, or `false`.
1206 /// `partition()` returns a pair, all of the elements for which it returned
1207 /// `true`, and all of the elements for which it returned `false`.
1214 /// let a = [1, 2, 3];
1216 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1217 /// .partition(|&n| n % 2 == 0);
1219 /// assert_eq!(even, vec![2]);
1220 /// assert_eq!(odd, vec![1, 3]);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 fn partition<B, F>(self, mut f: F) -> (B, B) where
1225 B: Default + Extend<Self::Item>,
1226 F: FnMut(&Self::Item) -> bool
1228 let mut left: B = Default::default();
1229 let mut right: B = Default::default();
1233 left.extend(Some(x))
1235 right.extend(Some(x))
1242 /// An iterator adaptor that applies a function, producing a single, final value.
1244 /// `fold()` takes two arguments: an initial value, and a closure with two
1245 /// arguments: an 'accumulator', and an element. The closure returns the value that
1246 /// the accumulator should have for the next iteration.
1248 /// The initial value is the value the accumulator will have on the first
1251 /// After applying this closure to every element of the iterator, `fold()`
1252 /// returns the accumulator.
1254 /// This operation is sometimes called 'reduce' or 'inject'.
1256 /// Folding is useful whenever you have a collection of something, and want
1257 /// to produce a single value from it.
1264 /// let a = [1, 2, 3];
1266 /// // the sum of all of the elements of a
1267 /// let sum = a.iter()
1268 /// .fold(0, |acc, &x| acc + x);
1270 /// assert_eq!(sum, 6);
1273 /// Let's walk through each step of the iteration here:
1275 /// | element | acc | x | result |
1276 /// |---------|-----|---|--------|
1278 /// | 1 | 0 | 1 | 1 |
1279 /// | 2 | 1 | 2 | 3 |
1280 /// | 3 | 3 | 3 | 6 |
1282 /// And so, our final result, `6`.
1284 /// It's common for people who haven't used iterators a lot to
1285 /// use a `for` loop with a list of things to build up a result. Those
1286 /// can be turned into `fold()`s:
1289 /// let numbers = [1, 2, 3, 4, 5];
1291 /// let mut result = 0;
1294 /// for i in &numbers {
1295 /// result = result + i;
1299 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1301 /// // they're the same
1302 /// assert_eq!(result, result2);
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 fn fold<B, F>(self, init: B, mut f: F) -> B where
1307 Self: Sized, F: FnMut(B, Self::Item) -> B,
1309 let mut accum = init;
1311 accum = f(accum, x);
1316 /// Tests if every element of the iterator matches a predicate.
1318 /// `all()` takes a closure that returns `true` or `false`. It applies
1319 /// this closure to each element of the iterator, and if they all return
1320 /// `true`, then so does `all()`. If any of them return `false`, it
1321 /// returns `false`.
1323 /// `all()` is short-circuiting; in other words, it will stop processing
1324 /// as soon as it finds a `false`, given that no matter what else happens,
1325 /// the result will also be `false`.
1327 /// An empty iterator returns `true`.
1334 /// let a = [1, 2, 3];
1336 /// assert!(a.iter().all(|&x| x > 0));
1338 /// assert!(!a.iter().all(|&x| x > 2));
1341 /// Stopping at the first `false`:
1344 /// let a = [1, 2, 3];
1346 /// let mut iter = a.iter();
1348 /// assert!(!iter.all(|&x| x != 2));
1350 /// // we can still use `iter`, as there are more elements.
1351 /// assert_eq!(iter.next(), Some(&3));
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 fn all<F>(&mut self, mut f: F) -> bool where
1356 Self: Sized, F: FnMut(Self::Item) -> bool
1366 /// Tests if any element of the iterator matches a predicate.
1368 /// `any()` takes a closure that returns `true` or `false`. It applies
1369 /// this closure to each element of the iterator, and if any of them return
1370 /// `true`, then so does `any()`. If they all return `false`, it
1371 /// returns `false`.
1373 /// `any()` is short-circuiting; in other words, it will stop processing
1374 /// as soon as it finds a `true`, given that no matter what else happens,
1375 /// the result will also be `true`.
1377 /// An empty iterator returns `false`.
1384 /// let a = [1, 2, 3];
1386 /// assert!(a.iter().any(|&x| x > 0));
1388 /// assert!(!a.iter().any(|&x| x > 5));
1391 /// Stopping at the first `true`:
1394 /// let a = [1, 2, 3];
1396 /// let mut iter = a.iter();
1398 /// assert!(iter.any(|&x| x != 2));
1400 /// // we can still use `iter`, as there are more elements.
1401 /// assert_eq!(iter.next(), Some(&2));
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 fn any<F>(&mut self, mut f: F) -> bool where
1407 F: FnMut(Self::Item) -> bool
1417 /// Searches for an element of an iterator that satisfies a predicate.
1419 /// `find()` takes a closure that returns `true` or `false`. It applies
1420 /// this closure to each element of the iterator, and if any of them return
1421 /// `true`, then `find()` returns `Some(element)`. If they all return
1422 /// `false`, it returns `None`.
1424 /// `find()` is short-circuiting; in other words, it will stop processing
1425 /// as soon as the closure returns `true`.
1427 /// Because `find()` takes a reference, and many iterators iterate over
1428 /// references, this leads to a possibly confusing situation where the
1429 /// argument is a double reference. You can see this effect in the
1430 /// examples below, with `&&x`.
1437 /// let a = [1, 2, 3];
1439 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1441 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1444 /// Stopping at the first `true`:
1447 /// let a = [1, 2, 3];
1449 /// let mut iter = a.iter();
1451 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1453 /// // we can still use `iter`, as there are more elements.
1454 /// assert_eq!(iter.next(), Some(&3));
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1460 P: FnMut(&Self::Item) -> bool,
1463 if predicate(&x) { return Some(x) }
1468 /// Searches for an element in an iterator, returning its index.
1470 /// `position()` takes a closure that returns `true` or `false`. It applies
1471 /// this closure to each element of the iterator, and if one of them
1472 /// returns `true`, then `position()` returns `Some(index)`. If all of
1473 /// them return `false`, it returns `None`.
1475 /// `position()` is short-circuiting; in other words, it will stop
1476 /// processing as soon as it finds a `true`.
1478 /// # Overflow Behavior
1480 /// The method does no guarding against overflows, so if there are more
1481 /// than `usize::MAX` non-matching elements, it either produces the wrong
1482 /// result or panics. If debug assertions are enabled, a panic is
1487 /// This function might panic if the iterator has more than `usize::MAX`
1488 /// non-matching elements.
1495 /// let a = [1, 2, 3];
1497 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1499 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1502 /// Stopping at the first `true`:
1505 /// let a = [1, 2, 3];
1507 /// let mut iter = a.iter();
1509 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1511 /// // we can still use `iter`, as there are more elements.
1512 /// assert_eq!(iter.next(), Some(&3));
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1518 P: FnMut(Self::Item) -> bool,
1520 // `enumerate` might overflow.
1521 for (i, x) in self.enumerate() {
1529 /// Searches for an element in an iterator from the right, returning its
1532 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1533 /// this closure to each element of the iterator, starting from the end,
1534 /// and if one of them returns `true`, then `rposition()` returns
1535 /// `Some(index)`. If all of them return `false`, it returns `None`.
1537 /// `rposition()` is short-circuiting; in other words, it will stop
1538 /// processing as soon as it finds a `true`.
1545 /// let a = [1, 2, 3];
1547 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1549 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1552 /// Stopping at the first `true`:
1555 /// let a = [1, 2, 3];
1557 /// let mut iter = a.iter();
1559 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1561 /// // we can still use `iter`, as there are more elements.
1562 /// assert_eq!(iter.next(), Some(&1));
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1567 P: FnMut(Self::Item) -> bool,
1568 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1570 let mut i = self.len();
1572 while let Some(v) = self.next_back() {
1576 // No need for an overflow check here, because `ExactSizeIterator`
1577 // implies that the number of elements fits into a `usize`.
1583 /// Returns the maximum element of an iterator.
1585 /// If the two elements are equally maximum, the latest element is
1593 /// let a = [1, 2, 3];
1595 /// assert_eq!(a.iter().max(), Some(&3));
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1603 // switch to y even if it is only equal, to preserve
1605 |_, x, _, y| *x <= *y)
1609 /// Returns the minimum element of an iterator.
1611 /// If the two elements are equally minimum, the first element is
1619 /// let a = [1, 2, 3];
1621 /// assert_eq!(a.iter().min(), Some(&1));
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1629 // only switch to y if it is strictly smaller, to
1630 // preserve stability.
1631 |_, x, _, y| *x > *y)
1635 /// Returns the element that gives the maximum value from the
1636 /// specified function.
1638 /// Returns the rightmost element if the comparison determines two elements
1639 /// to be equally maximum.
1644 /// let a = [-3_i32, 0, 1, 5, -10];
1645 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1648 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1649 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1650 where Self: Sized, F: FnMut(&Self::Item) -> B,
1654 // switch to y even if it is only equal, to preserve
1656 |x_p, _, y_p, _| x_p <= y_p)
1660 /// Returns the element that gives the minimum value from the
1661 /// specified function.
1663 /// Returns the latest element if the comparison determines two elements
1664 /// to be equally minimum.
1669 /// let a = [-3_i32, 0, 1, 5, -10];
1670 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1672 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1673 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1674 where Self: Sized, F: FnMut(&Self::Item) -> B,
1678 // only switch to y if it is strictly smaller, to
1679 // preserve stability.
1680 |x_p, _, y_p, _| x_p > y_p)
1684 /// Reverses an iterator's direction.
1686 /// Usually, iterators iterate from left to right. After using `rev()`,
1687 /// an iterator will instead iterate from right to left.
1689 /// This is only possible if the iterator has an end, so `rev()` only
1690 /// works on [`DoubleEndedIterator`]s.
1692 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1697 /// let a = [1, 2, 3];
1699 /// let mut iter = a.iter().rev();
1701 /// assert_eq!(iter.next(), Some(&3));
1702 /// assert_eq!(iter.next(), Some(&2));
1703 /// assert_eq!(iter.next(), Some(&1));
1705 /// assert_eq!(iter.next(), None);
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1713 /// Converts an iterator of pairs into a pair of containers.
1715 /// `unzip()` consumes an entire iterator of pairs, producing two
1716 /// collections: one from the left elements of the pairs, and one
1717 /// from the right elements.
1719 /// This function is, in some sense, the opposite of [`zip()`].
1721 /// [`zip()`]: #method.zip
1728 /// let a = [(1, 2), (3, 4)];
1730 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1732 /// assert_eq!(left, [1, 3]);
1733 /// assert_eq!(right, [2, 4]);
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1737 FromA: Default + Extend<A>,
1738 FromB: Default + Extend<B>,
1739 Self: Sized + Iterator<Item=(A, B)>,
1741 let mut ts: FromA = Default::default();
1742 let mut us: FromB = Default::default();
1744 for (t, u) in self {
1752 /// Creates an iterator which `clone()`s all of its elements.
1754 /// This is useful when you have an iterator over `&T`, but you need an
1755 /// iterator over `T`.
1762 /// let a = [1, 2, 3];
1764 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1766 /// // cloned is the same as .map(|&x| x), for integers
1767 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1769 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1770 /// assert_eq!(v_map, vec![1, 2, 3]);
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1774 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1779 /// Repeats an iterator endlessly.
1781 /// Instead of stopping at `None`, the iterator will instead start again,
1782 /// from the beginning. After iterating again, it will start at the
1783 /// beginning again. And again. And again. Forever.
1790 /// let a = [1, 2, 3];
1792 /// let mut it = a.iter().cycle();
1794 /// assert_eq!(it.next(), Some(&1));
1795 /// assert_eq!(it.next(), Some(&2));
1796 /// assert_eq!(it.next(), Some(&3));
1797 /// assert_eq!(it.next(), Some(&1));
1798 /// assert_eq!(it.next(), Some(&2));
1799 /// assert_eq!(it.next(), Some(&3));
1800 /// assert_eq!(it.next(), Some(&1));
1802 #[stable(feature = "rust1", since = "1.0.0")]
1804 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1805 Cycle{orig: self.clone(), iter: self}
1808 /// Sums the elements of an iterator.
1810 /// Takes each element, adds them together, and returns the result.
1812 /// An empty iterator returns the zero value of the type.
1816 /// When calling `sum` and a primitive integer type is being returned, this
1817 /// method will panic if the computation overflows.
1824 /// let a = [1, 2, 3];
1825 /// let sum: i32 = a.iter().sum();
1827 /// assert_eq!(sum, 6);
1829 #[stable(feature = "iter_arith", since = "1.11.0")]
1830 fn sum<S>(self) -> S
1837 /// Iterates over the entire iterator, multiplying all the elements
1839 /// An empty iterator returns the one value of the type.
1843 /// When calling `product` and a primitive integer type is being returned,
1844 /// this method will panic if the computation overflows.
1849 /// fn factorial(n: u32) -> u32 {
1850 /// (1..).take_while(|&i| i <= n).product()
1852 /// assert_eq!(factorial(0), 1);
1853 /// assert_eq!(factorial(1), 1);
1854 /// assert_eq!(factorial(5), 120);
1856 #[stable(feature = "iter_arith", since = "1.11.0")]
1857 fn product<P>(self) -> P
1859 P: Product<Self::Item>,
1861 Product::product(self)
1864 /// Lexicographically compares the elements of this `Iterator` with those
1866 #[stable(feature = "iter_order", since = "1.5.0")]
1867 fn cmp<I>(mut self, other: I) -> Ordering where
1868 I: IntoIterator<Item = Self::Item>,
1872 let mut other = other.into_iter();
1875 match (self.next(), other.next()) {
1876 (None, None) => return Ordering::Equal,
1877 (None, _ ) => return Ordering::Less,
1878 (_ , None) => return Ordering::Greater,
1879 (Some(x), Some(y)) => match x.cmp(&y) {
1880 Ordering::Equal => (),
1881 non_eq => return non_eq,
1887 /// Lexicographically compares the elements of this `Iterator` with those
1889 #[stable(feature = "iter_order", since = "1.5.0")]
1890 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1892 Self::Item: PartialOrd<I::Item>,
1895 let mut other = other.into_iter();
1898 match (self.next(), other.next()) {
1899 (None, None) => return Some(Ordering::Equal),
1900 (None, _ ) => return Some(Ordering::Less),
1901 (_ , None) => return Some(Ordering::Greater),
1902 (Some(x), Some(y)) => match x.partial_cmp(&y) {
1903 Some(Ordering::Equal) => (),
1904 non_eq => return non_eq,
1910 /// Determines if the elements of this `Iterator` are equal to those of
1912 #[stable(feature = "iter_order", since = "1.5.0")]
1913 fn eq<I>(mut self, other: I) -> bool where
1915 Self::Item: PartialEq<I::Item>,
1918 let mut other = other.into_iter();
1921 match (self.next(), other.next()) {
1922 (None, None) => return true,
1923 (None, _) | (_, None) => return false,
1924 (Some(x), Some(y)) => if x != y { return false },
1929 /// Determines if the elements of this `Iterator` are unequal to those of
1931 #[stable(feature = "iter_order", since = "1.5.0")]
1932 fn ne<I>(mut self, other: I) -> bool where
1934 Self::Item: PartialEq<I::Item>,
1937 let mut other = other.into_iter();
1940 match (self.next(), other.next()) {
1941 (None, None) => return false,
1942 (None, _) | (_, None) => return true,
1943 (Some(x), Some(y)) => if x.ne(&y) { return true },
1948 /// Determines if the elements of this `Iterator` are lexicographically
1949 /// less than those of another.
1950 #[stable(feature = "iter_order", since = "1.5.0")]
1951 fn lt<I>(mut self, other: I) -> bool where
1953 Self::Item: PartialOrd<I::Item>,
1956 let mut other = other.into_iter();
1959 match (self.next(), other.next()) {
1960 (None, None) => return false,
1961 (None, _ ) => return true,
1962 (_ , None) => return false,
1963 (Some(x), Some(y)) => {
1964 match x.partial_cmp(&y) {
1965 Some(Ordering::Less) => return true,
1966 Some(Ordering::Equal) => {}
1967 Some(Ordering::Greater) => return false,
1968 None => return false,
1975 /// Determines if the elements of this `Iterator` are lexicographically
1976 /// less or equal to those of another.
1977 #[stable(feature = "iter_order", since = "1.5.0")]
1978 fn le<I>(mut self, other: I) -> bool where
1980 Self::Item: PartialOrd<I::Item>,
1983 let mut other = other.into_iter();
1986 match (self.next(), other.next()) {
1987 (None, None) => return true,
1988 (None, _ ) => return true,
1989 (_ , None) => return false,
1990 (Some(x), Some(y)) => {
1991 match x.partial_cmp(&y) {
1992 Some(Ordering::Less) => return true,
1993 Some(Ordering::Equal) => {}
1994 Some(Ordering::Greater) => return false,
1995 None => return false,
2002 /// Determines if the elements of this `Iterator` are lexicographically
2003 /// greater than those of another.
2004 #[stable(feature = "iter_order", since = "1.5.0")]
2005 fn gt<I>(mut self, other: I) -> bool where
2007 Self::Item: PartialOrd<I::Item>,
2010 let mut other = other.into_iter();
2013 match (self.next(), other.next()) {
2014 (None, None) => return false,
2015 (None, _ ) => return false,
2016 (_ , None) => return true,
2017 (Some(x), Some(y)) => {
2018 match x.partial_cmp(&y) {
2019 Some(Ordering::Less) => return false,
2020 Some(Ordering::Equal) => {}
2021 Some(Ordering::Greater) => return true,
2022 None => return false,
2029 /// Determines if the elements of this `Iterator` are lexicographically
2030 /// greater than or equal to those of another.
2031 #[stable(feature = "iter_order", since = "1.5.0")]
2032 fn ge<I>(mut self, other: I) -> bool where
2034 Self::Item: PartialOrd<I::Item>,
2037 let mut other = other.into_iter();
2040 match (self.next(), other.next()) {
2041 (None, None) => return true,
2042 (None, _ ) => return false,
2043 (_ , None) => return true,
2044 (Some(x), Some(y)) => {
2045 match x.partial_cmp(&y) {
2046 Some(Ordering::Less) => return false,
2047 Some(Ordering::Equal) => {}
2048 Some(Ordering::Greater) => return true,
2049 None => return false,
2057 /// Select an element from an iterator based on the given projection
2058 /// and "comparison" function.
2060 /// This is an idiosyncratic helper to try to factor out the
2061 /// commonalities of {max,min}{,_by}. In particular, this avoids
2062 /// having to implement optimizations several times.
2064 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2066 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2068 FProj: FnMut(&I::Item) -> B,
2069 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2071 // start with the first element as our selection. This avoids
2072 // having to use `Option`s inside the loop, translating to a
2073 // sizeable performance gain (6x in one case).
2074 it.next().map(|mut sel| {
2075 let mut sel_p = f_proj(&sel);
2078 let x_p = f_proj(&x);
2079 if f_cmp(&sel_p, &sel, &x_p, &x) {
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2090 type Item = I::Item;
2091 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2092 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }