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
43 /// [`None`]: ../../std/option/enum.Option.html#variant.None
44 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
51 /// let a = [1, 2, 3];
53 /// let mut iter = a.iter();
55 /// // A call to next() returns the next value...
56 /// assert_eq!(Some(&1), iter.next());
57 /// assert_eq!(Some(&2), iter.next());
58 /// assert_eq!(Some(&3), iter.next());
60 /// // ... and then None once it's over.
61 /// assert_eq!(None, iter.next());
63 /// // More calls may or may not return None. Here, they always will.
64 /// assert_eq!(None, iter.next());
65 /// assert_eq!(None, iter.next());
67 #[stable(feature = "rust1", since = "1.0.0")]
68 fn next(&mut self) -> Option<Self::Item>;
70 /// Returns the bounds on the remaining length of the iterator.
72 /// Specifically, `size_hint()` returns a tuple where the first element
73 /// is the lower bound, and the second element is the upper bound.
75 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
76 /// A [`None`] here means that either there is no known upper bound, or the
77 /// upper bound is larger than [`usize`].
79 /// # Implementation notes
81 /// It is not enforced that an iterator implementation yields the declared
82 /// number of elements. A buggy iterator may yield less than the lower bound
83 /// or more than the upper bound of elements.
85 /// `size_hint()` is primarily intended to be used for optimizations such as
86 /// reserving space for the elements of the iterator, but must not be
87 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
88 /// implementation of `size_hint()` should not lead to memory safety
91 /// That said, the implementation should provide a correct estimation,
92 /// because otherwise it would be a violation of the trait's protocol.
94 /// The default implementation returns `(0, None)` which is correct for any
97 /// [`usize`]: ../../std/primitive.usize.html
98 /// [`Option`]: ../../std/option/enum.Option.html
99 /// [`None`]: ../../std/option/enum.Option.html#variant.None
106 /// let a = [1, 2, 3];
107 /// let iter = a.iter();
109 /// assert_eq!((3, Some(3)), iter.size_hint());
112 /// A more complex example:
115 /// // The even numbers from zero to ten.
116 /// let iter = (0..10).filter(|x| x % 2 == 0);
118 /// // We might iterate from zero to ten times. Knowing that it's five
119 /// // exactly wouldn't be possible without executing filter().
120 /// assert_eq!((0, Some(10)), iter.size_hint());
122 /// // Let's add one five more numbers with chain()
123 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
125 /// // now both bounds are increased by five
126 /// assert_eq!((5, Some(15)), iter.size_hint());
129 /// Returning `None` for an upper bound:
132 /// // an infinite iterator has no upper bound
135 /// assert_eq!((0, None), iter.size_hint());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
141 /// Consumes the iterator, counting the number of iterations and returning it.
143 /// This method will evaluate the iterator until its [`next`] returns
144 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
145 /// times it called [`next`].
147 /// [`next`]: #tymethod.next
148 /// [`None`]: ../../std/option/enum.Option.html#variant.None
150 /// # Overflow Behavior
152 /// The method does no guarding against overflows, so counting elements of
153 /// an iterator with more than [`usize::MAX`] elements either produces the
154 /// wrong result or panics. If debug assertions are enabled, a panic is
159 /// This function might panic if the iterator has more than [`usize::MAX`]
162 /// [`usize::MAX`]: ../../std/isize/constant.MAX.html
169 /// let a = [1, 2, 3];
170 /// assert_eq!(a.iter().count(), 3);
172 /// let a = [1, 2, 3, 4, 5];
173 /// assert_eq!(a.iter().count(), 5);
176 #[rustc_inherit_overflow_checks]
177 #[stable(feature = "rust1", since = "1.0.0")]
178 fn count(self) -> usize where Self: Sized {
180 self.fold(0, |cnt, _| cnt + 1)
183 /// Consumes the iterator, returning the last element.
185 /// This method will evaluate the iterator until it returns [`None`]. While
186 /// doing so, it keeps track of the current element. After [`None`] is
187 /// returned, `last()` will then return the last element it saw.
189 /// [`None`]: ../../std/option/enum.Option.html#variant.None
196 /// let a = [1, 2, 3];
197 /// assert_eq!(a.iter().last(), Some(&3));
199 /// let a = [1, 2, 3, 4, 5];
200 /// assert_eq!(a.iter().last(), Some(&5));
203 #[stable(feature = "rust1", since = "1.0.0")]
204 fn last(self) -> Option<Self::Item> where Self: Sized {
206 for x in self { last = Some(x); }
210 /// Returns the `n`th element of the iterator.
212 /// Like most indexing operations, the count starts from zero, so `nth(0)`
213 /// returns the first value, `nth(1)` the second, and so on.
215 /// Note that all preceding elements, as well as the returned element, will be
216 /// consumed from the iterator. That means that the preceding elements will be
217 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
218 /// will return different elements.
220 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
223 /// [`None`]: ../../std/option/enum.Option.html#variant.None
230 /// let a = [1, 2, 3];
231 /// assert_eq!(a.iter().nth(1), Some(&2));
234 /// Calling `nth()` multiple times doesn't rewind the iterator:
237 /// let a = [1, 2, 3];
239 /// let mut iter = a.iter();
241 /// assert_eq!(iter.nth(1), Some(&2));
242 /// assert_eq!(iter.nth(1), None);
245 /// Returning `None` if there are less than `n + 1` elements:
248 /// let a = [1, 2, 3];
249 /// assert_eq!(a.iter().nth(10), None);
252 #[stable(feature = "rust1", since = "1.0.0")]
253 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
255 if n == 0 { return Some(x) }
261 /// Takes two iterators and creates a new iterator over both in sequence.
263 /// `chain()` will return a new iterator which will first iterate over
264 /// values from the first iterator and then over values from the second
267 /// In other words, it links two iterators together, in a chain. 🔗
274 /// let a1 = [1, 2, 3];
275 /// let a2 = [4, 5, 6];
277 /// let mut iter = a1.iter().chain(a2.iter());
279 /// assert_eq!(iter.next(), Some(&1));
280 /// assert_eq!(iter.next(), Some(&2));
281 /// assert_eq!(iter.next(), Some(&3));
282 /// assert_eq!(iter.next(), Some(&4));
283 /// assert_eq!(iter.next(), Some(&5));
284 /// assert_eq!(iter.next(), Some(&6));
285 /// assert_eq!(iter.next(), None);
288 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
289 /// anything that can be converted into an [`Iterator`], not just an
290 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
291 /// [`IntoIterator`], and so can be passed to `chain()` directly:
293 /// [`IntoIterator`]: trait.IntoIterator.html
294 /// [`Iterator`]: trait.Iterator.html
297 /// let s1 = &[1, 2, 3];
298 /// let s2 = &[4, 5, 6];
300 /// let mut iter = s1.iter().chain(s2);
302 /// assert_eq!(iter.next(), Some(&1));
303 /// assert_eq!(iter.next(), Some(&2));
304 /// assert_eq!(iter.next(), Some(&3));
305 /// assert_eq!(iter.next(), Some(&4));
306 /// assert_eq!(iter.next(), Some(&5));
307 /// assert_eq!(iter.next(), Some(&6));
308 /// assert_eq!(iter.next(), None);
311 #[stable(feature = "rust1", since = "1.0.0")]
312 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
313 Self: Sized, U: IntoIterator<Item=Self::Item>,
315 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
318 /// 'Zips up' two iterators into a single iterator of pairs.
320 /// `zip()` returns a new iterator that will iterate over two other
321 /// iterators, returning a tuple where the first element comes from the
322 /// first iterator, and the second element comes from the second iterator.
324 /// In other words, it zips two iterators together, into a single one.
326 /// When either iterator returns [`None`], all further calls to [`next`]
327 /// will return [`None`].
334 /// let a1 = [1, 2, 3];
335 /// let a2 = [4, 5, 6];
337 /// let mut iter = a1.iter().zip(a2.iter());
339 /// assert_eq!(iter.next(), Some((&1, &4)));
340 /// assert_eq!(iter.next(), Some((&2, &5)));
341 /// assert_eq!(iter.next(), Some((&3, &6)));
342 /// assert_eq!(iter.next(), None);
345 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
346 /// anything that can be converted into an [`Iterator`], not just an
347 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
348 /// [`IntoIterator`], and so can be passed to `zip()` directly:
350 /// [`IntoIterator`]: trait.IntoIterator.html
351 /// [`Iterator`]: trait.Iterator.html
354 /// let s1 = &[1, 2, 3];
355 /// let s2 = &[4, 5, 6];
357 /// let mut iter = s1.iter().zip(s2);
359 /// assert_eq!(iter.next(), Some((&1, &4)));
360 /// assert_eq!(iter.next(), Some((&2, &5)));
361 /// assert_eq!(iter.next(), Some((&3, &6)));
362 /// assert_eq!(iter.next(), None);
365 /// `zip()` is often used to zip an infinite iterator to a finite one.
366 /// This works because the finite iterator will eventually return [`None`],
367 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
370 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
372 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
374 /// assert_eq!((0, 'f'), enumerate[0]);
375 /// assert_eq!((0, 'f'), zipper[0]);
377 /// assert_eq!((1, 'o'), enumerate[1]);
378 /// assert_eq!((1, 'o'), zipper[1]);
380 /// assert_eq!((2, 'o'), enumerate[2]);
381 /// assert_eq!((2, 'o'), zipper[2]);
384 /// [`enumerate`]: trait.Iterator.html#method.enumerate
385 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
386 /// [`None`]: ../../std/option/enum.Option.html#variant.None
388 #[stable(feature = "rust1", since = "1.0.0")]
389 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
390 Self: Sized, U: IntoIterator
392 Zip::new(self, other.into_iter())
395 /// Takes a closure and creates an iterator which calls that closure on each
398 /// `map()` transforms one iterator into another, by means of its argument:
399 /// something that implements `FnMut`. It produces a new iterator which
400 /// calls this closure on each element of the original iterator.
402 /// If you are good at thinking in types, you can think of `map()` like this:
403 /// If you have an iterator that gives you elements of some type `A`, and
404 /// you want an iterator of some other type `B`, you can use `map()`,
405 /// passing a closure that takes an `A` and returns a `B`.
407 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
408 /// lazy, it is best used when you're already working with other iterators.
409 /// If you're doing some sort of looping for a side effect, it's considered
410 /// more idiomatic to use [`for`] than `map()`.
412 /// [`for`]: ../../book/first-edition/loops.html#for
419 /// let a = [1, 2, 3];
421 /// let mut iter = a.into_iter().map(|x| 2 * x);
423 /// assert_eq!(iter.next(), Some(2));
424 /// assert_eq!(iter.next(), Some(4));
425 /// assert_eq!(iter.next(), Some(6));
426 /// assert_eq!(iter.next(), None);
429 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
432 /// # #![allow(unused_must_use)]
433 /// // don't do this:
434 /// (0..5).map(|x| println!("{}", x));
436 /// // it won't even execute, as it is lazy. Rust will warn you about this.
438 /// // Instead, use for:
440 /// println!("{}", x);
444 #[stable(feature = "rust1", since = "1.0.0")]
445 fn map<B, F>(self, f: F) -> Map<Self, F> where
446 Self: Sized, F: FnMut(Self::Item) -> B,
448 Map{iter: self, f: f}
451 /// Creates an iterator which uses a closure to determine if an element
452 /// should be yielded.
454 /// The closure must return `true` or `false`. `filter()` creates an
455 /// iterator which calls this closure on each element. If the closure
456 /// returns `true`, then the element is returned. If the closure returns
457 /// `false`, it will try again, and call the closure on the next element,
458 /// seeing if it passes the test.
465 /// let a = [0i32, 1, 2];
467 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
469 /// assert_eq!(iter.next(), Some(&1));
470 /// assert_eq!(iter.next(), Some(&2));
471 /// assert_eq!(iter.next(), None);
474 /// Because the closure passed to `filter()` takes a reference, and many
475 /// iterators iterate over references, this leads to a possibly confusing
476 /// situation, where the type of the closure is a double reference:
479 /// let a = [0, 1, 2];
481 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
483 /// assert_eq!(iter.next(), Some(&2));
484 /// assert_eq!(iter.next(), None);
487 /// It's common to instead use destructuring on the argument to strip away
491 /// let a = [0, 1, 2];
493 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
495 /// assert_eq!(iter.next(), Some(&2));
496 /// assert_eq!(iter.next(), None);
502 /// let a = [0, 1, 2];
504 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
506 /// assert_eq!(iter.next(), Some(&2));
507 /// assert_eq!(iter.next(), None);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
514 Self: Sized, P: FnMut(&Self::Item) -> bool,
516 Filter{iter: self, predicate: predicate}
519 /// Creates an iterator that both filters and maps.
521 /// The closure must return an [`Option<T>`]. `filter_map` creates an
522 /// iterator which calls this closure on each element. If the closure
523 /// returns [`Some(element)`][`Some`], then that element is returned. If the
524 /// closure returns [`None`], it will try again, and call the closure on the
525 /// next element, seeing if it will return [`Some`].
527 /// Why `filter_map` and not just [`filter`].[`map`]? The key is in this
530 /// [`filter`]: #method.filter
531 /// [`map`]: #method.map
533 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
535 /// In other words, it removes the [`Option<T>`] layer automatically. If your
536 /// mapping is already returning an [`Option<T>`] and you want to skip over
537 /// [`None`]s, then `filter_map` is much, much nicer to use.
544 /// let a = ["1", "2", "lol"];
546 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
548 /// assert_eq!(iter.next(), Some(1));
549 /// assert_eq!(iter.next(), Some(2));
550 /// assert_eq!(iter.next(), None);
553 /// Here's the same example, but with [`filter`] and [`map`]:
556 /// let a = ["1", "2", "lol"];
558 /// let mut iter = a.iter()
559 /// .map(|s| s.parse().ok())
560 /// .filter(|s| s.is_some());
562 /// assert_eq!(iter.next(), Some(Some(1)));
563 /// assert_eq!(iter.next(), Some(Some(2)));
564 /// assert_eq!(iter.next(), None);
567 /// There's an extra layer of [`Some`] in there.
569 /// [`Option<T>`]: ../../std/option/enum.Option.html
570 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
571 /// [`None`]: ../../std/option/enum.Option.html#variant.None
573 #[stable(feature = "rust1", since = "1.0.0")]
574 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
575 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
577 FilterMap { iter: self, f: f }
580 /// Creates an iterator which gives the current iteration count as well as
583 /// The iterator returned yields pairs `(i, val)`, where `i` is the
584 /// current index of iteration and `val` is the value returned by the
587 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
588 /// different sized integer, the [`zip`] function provides similar
591 /// # Overflow Behavior
593 /// The method does no guarding against overflows, so enumerating more than
594 /// [`usize::MAX`] elements either produces the wrong result or panics. If
595 /// debug assertions are enabled, a panic is guaranteed.
599 /// The returned iterator might panic if the to-be-returned index would
600 /// overflow a [`usize`].
602 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
603 /// [`usize`]: ../../std/primitive.usize.html
604 /// [`zip`]: #method.zip
609 /// let a = ['a', 'b', 'c'];
611 /// let mut iter = a.iter().enumerate();
613 /// assert_eq!(iter.next(), Some((0, &'a')));
614 /// assert_eq!(iter.next(), Some((1, &'b')));
615 /// assert_eq!(iter.next(), Some((2, &'c')));
616 /// assert_eq!(iter.next(), None);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
621 Enumerate { iter: self, count: 0 }
624 /// Creates an iterator which can use `peek` to look at the next element of
625 /// the iterator without consuming it.
627 /// Adds a [`peek`] method to an iterator. See its documentation for
628 /// more information.
630 /// Note that the underlying iterator is still advanced when [`peek`] is
631 /// called for the first time: In order to retrieve the next element,
632 /// [`next`] is called on the underlying iterator, hence any side effects of
633 /// the [`next`] method will occur.
635 /// [`peek`]: struct.Peekable.html#method.peek
636 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
643 /// let xs = [1, 2, 3];
645 /// let mut iter = xs.iter().peekable();
647 /// // peek() lets us see into the future
648 /// assert_eq!(iter.peek(), Some(&&1));
649 /// assert_eq!(iter.next(), Some(&1));
651 /// assert_eq!(iter.next(), Some(&2));
653 /// // we can peek() multiple times, the iterator won't advance
654 /// assert_eq!(iter.peek(), Some(&&3));
655 /// assert_eq!(iter.peek(), Some(&&3));
657 /// assert_eq!(iter.next(), Some(&3));
659 /// // after the iterator is finished, so is peek()
660 /// assert_eq!(iter.peek(), None);
661 /// assert_eq!(iter.next(), None);
664 #[stable(feature = "rust1", since = "1.0.0")]
665 fn peekable(self) -> Peekable<Self> where Self: Sized {
666 Peekable{iter: self, peeked: None}
669 /// Creates an iterator that [`skip`]s elements based on a predicate.
671 /// [`skip`]: #method.skip
673 /// `skip_while()` takes a closure as an argument. It will call this
674 /// closure on each element of the iterator, and ignore elements
675 /// until it returns `false`.
677 /// After `false` is returned, `skip_while()`'s job is over, and the
678 /// rest of the elements are yielded.
685 /// let a = [-1i32, 0, 1];
687 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
689 /// assert_eq!(iter.next(), Some(&0));
690 /// assert_eq!(iter.next(), Some(&1));
691 /// assert_eq!(iter.next(), None);
694 /// Because the closure passed to `skip_while()` takes a reference, and many
695 /// iterators iterate over references, this leads to a possibly confusing
696 /// situation, where the type of the closure is a double reference:
699 /// let a = [-1, 0, 1];
701 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
703 /// assert_eq!(iter.next(), Some(&0));
704 /// assert_eq!(iter.next(), Some(&1));
705 /// assert_eq!(iter.next(), None);
708 /// Stopping after an initial `false`:
711 /// let a = [-1, 0, 1, -2];
713 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
715 /// assert_eq!(iter.next(), Some(&0));
716 /// assert_eq!(iter.next(), Some(&1));
718 /// // while this would have been false, since we already got a false,
719 /// // skip_while() isn't used any more
720 /// assert_eq!(iter.next(), Some(&-2));
722 /// assert_eq!(iter.next(), None);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
727 Self: Sized, P: FnMut(&Self::Item) -> bool,
729 SkipWhile{iter: self, flag: false, predicate: predicate}
732 /// Creates an iterator that yields elements based on a predicate.
734 /// `take_while()` takes a closure as an argument. It will call this
735 /// closure on each element of the iterator, and yield elements
736 /// while it returns `true`.
738 /// After `false` is returned, `take_while()`'s job is over, and the
739 /// rest of the elements are ignored.
746 /// let a = [-1i32, 0, 1];
748 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
750 /// assert_eq!(iter.next(), Some(&-1));
751 /// assert_eq!(iter.next(), None);
754 /// Because the closure passed to `take_while()` takes a reference, and many
755 /// iterators iterate over references, this leads to a possibly confusing
756 /// situation, where the type of the closure is a double reference:
759 /// let a = [-1, 0, 1];
761 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
763 /// assert_eq!(iter.next(), Some(&-1));
764 /// assert_eq!(iter.next(), None);
767 /// Stopping after an initial `false`:
770 /// let a = [-1, 0, 1, -2];
772 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
774 /// assert_eq!(iter.next(), Some(&-1));
776 /// // We have more elements that are less than zero, but since we already
777 /// // got a false, take_while() isn't used any more
778 /// assert_eq!(iter.next(), None);
781 /// Because `take_while()` needs to look at the value in order to see if it
782 /// should be included or not, consuming iterators will see that it is
786 /// let a = [1, 2, 3, 4];
787 /// let mut iter = a.into_iter();
789 /// let result: Vec<i32> = iter.by_ref()
790 /// .take_while(|n| **n != 3)
794 /// assert_eq!(result, &[1, 2]);
796 /// let result: Vec<i32> = iter.cloned().collect();
798 /// assert_eq!(result, &[4]);
801 /// The `3` is no longer there, because it was consumed in order to see if
802 /// the iteration should stop, but wasn't placed back into the iterator or
803 /// some similar thing.
805 #[stable(feature = "rust1", since = "1.0.0")]
806 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
807 Self: Sized, P: FnMut(&Self::Item) -> bool,
809 TakeWhile{iter: self, flag: false, predicate: predicate}
812 /// Creates an iterator that skips the first `n` elements.
814 /// After they have been consumed, the rest of the elements are yielded.
821 /// let a = [1, 2, 3];
823 /// let mut iter = a.iter().skip(2);
825 /// assert_eq!(iter.next(), Some(&3));
826 /// assert_eq!(iter.next(), None);
829 #[stable(feature = "rust1", since = "1.0.0")]
830 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
831 Skip{iter: self, n: n}
834 /// Creates an iterator that yields its first `n` elements.
841 /// let a = [1, 2, 3];
843 /// let mut iter = a.iter().take(2);
845 /// assert_eq!(iter.next(), Some(&1));
846 /// assert_eq!(iter.next(), Some(&2));
847 /// assert_eq!(iter.next(), None);
850 /// `take()` is often used with an infinite iterator, to make it finite:
853 /// let mut iter = (0..).take(3);
855 /// assert_eq!(iter.next(), Some(0));
856 /// assert_eq!(iter.next(), Some(1));
857 /// assert_eq!(iter.next(), Some(2));
858 /// assert_eq!(iter.next(), None);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
863 Take{iter: self, n: n}
866 /// An iterator adaptor similar to [`fold`] that holds internal state and
867 /// produces a new iterator.
869 /// [`fold`]: #method.fold
871 /// `scan()` takes two arguments: an initial value which seeds the internal
872 /// state, and a closure with two arguments, the first being a mutable
873 /// reference to the internal state and the second an iterator element.
874 /// The closure can assign to the internal state to share state between
877 /// On iteration, the closure will be applied to each element of the
878 /// iterator and the return value from the closure, an [`Option`], is
879 /// yielded by the iterator.
881 /// [`Option`]: ../../std/option/enum.Option.html
888 /// let a = [1, 2, 3];
890 /// let mut iter = a.iter().scan(1, |state, &x| {
891 /// // each iteration, we'll multiply the state by the element
892 /// *state = *state * x;
894 /// // the value passed on to the next iteration
898 /// assert_eq!(iter.next(), Some(1));
899 /// assert_eq!(iter.next(), Some(2));
900 /// assert_eq!(iter.next(), Some(6));
901 /// assert_eq!(iter.next(), None);
904 #[stable(feature = "rust1", since = "1.0.0")]
905 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
906 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
908 Scan{iter: self, f: f, state: initial_state}
911 /// Creates an iterator that works like map, but flattens nested structure.
913 /// The [`map`] adapter is very useful, but only when the closure
914 /// argument produces values. If it produces an iterator instead, there's
915 /// an extra layer of indirection. `flat_map()` will remove this extra layer
918 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
919 /// one item for each element, and `flat_map()`'s closure returns an
920 /// iterator for each element.
922 /// [`map`]: #method.map
929 /// let words = ["alpha", "beta", "gamma"];
931 /// // chars() returns an iterator
932 /// let merged: String = words.iter()
933 /// .flat_map(|s| s.chars())
935 /// assert_eq!(merged, "alphabetagamma");
938 #[stable(feature = "rust1", since = "1.0.0")]
939 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
940 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
942 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
945 /// Creates an iterator which ends after the first [`None`].
947 /// After an iterator returns [`None`], future calls may or may not yield
948 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
949 /// [`None`] is given, it will always return [`None`] forever.
951 /// [`None`]: ../../std/option/enum.Option.html#variant.None
952 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
959 /// // an iterator which alternates between Some and None
960 /// struct Alternate {
964 /// impl Iterator for Alternate {
967 /// fn next(&mut self) -> Option<i32> {
968 /// let val = self.state;
969 /// self.state = self.state + 1;
971 /// // if it's even, Some(i32), else None
972 /// if val % 2 == 0 {
980 /// let mut iter = Alternate { state: 0 };
982 /// // we can see our iterator going back and forth
983 /// assert_eq!(iter.next(), Some(0));
984 /// assert_eq!(iter.next(), None);
985 /// assert_eq!(iter.next(), Some(2));
986 /// assert_eq!(iter.next(), None);
988 /// // however, once we fuse it...
989 /// let mut iter = iter.fuse();
991 /// assert_eq!(iter.next(), Some(4));
992 /// assert_eq!(iter.next(), None);
994 /// // it will always return None after the first time.
995 /// assert_eq!(iter.next(), None);
996 /// assert_eq!(iter.next(), None);
997 /// assert_eq!(iter.next(), None);
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 fn fuse(self) -> Fuse<Self> where Self: Sized {
1002 Fuse{iter: self, done: false}
1005 /// Do something with each element of an iterator, passing the value on.
1007 /// When using iterators, you'll often chain several of them together.
1008 /// While working on such code, you might want to check out what's
1009 /// happening at various parts in the pipeline. To do that, insert
1010 /// a call to `inspect()`.
1012 /// It's much more common for `inspect()` to be used as a debugging tool
1013 /// than to exist in your final code, but never say never.
1020 /// let a = [1, 4, 2, 3];
1022 /// // this iterator sequence is complex.
1023 /// let sum = a.iter()
1025 /// .filter(|&x| x % 2 == 0)
1026 /// .fold(0, |sum, i| sum + i);
1028 /// println!("{}", sum);
1030 /// // let's add some inspect() calls to investigate what's happening
1031 /// let sum = a.iter()
1033 /// .inspect(|x| println!("about to filter: {}", x))
1034 /// .filter(|&x| x % 2 == 0)
1035 /// .inspect(|x| println!("made it through filter: {}", x))
1036 /// .fold(0, |sum, i| sum + i);
1038 /// println!("{}", sum);
1041 /// This will print:
1044 /// about to filter: 1
1045 /// about to filter: 4
1046 /// made it through filter: 4
1047 /// about to filter: 2
1048 /// made it through filter: 2
1049 /// about to filter: 3
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1055 Self: Sized, F: FnMut(&Self::Item),
1057 Inspect{iter: self, f: f}
1060 /// Borrows an iterator, rather than consuming it.
1062 /// This is useful to allow applying iterator adaptors while still
1063 /// retaining ownership of the original iterator.
1070 /// let a = [1, 2, 3];
1072 /// let iter = a.into_iter();
1074 /// let sum: i32 = iter.take(5)
1075 /// .fold(0, |acc, &i| acc + i );
1077 /// assert_eq!(sum, 6);
1079 /// // if we try to use iter again, it won't work. The following line
1080 /// // gives "error: use of moved value: `iter`
1081 /// // assert_eq!(iter.next(), None);
1083 /// // let's try that again
1084 /// let a = [1, 2, 3];
1086 /// let mut iter = a.into_iter();
1088 /// // instead, we add in a .by_ref()
1089 /// let sum: i32 = iter.by_ref()
1091 /// .fold(0, |acc, &i| acc + i );
1093 /// assert_eq!(sum, 3);
1095 /// // now this is just fine:
1096 /// assert_eq!(iter.next(), Some(&3));
1097 /// assert_eq!(iter.next(), None);
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1102 /// Transforms an iterator into a collection.
1104 /// `collect()` can take anything iterable, and turn it into a relevant
1105 /// collection. This is one of the more powerful methods in the standard
1106 /// library, used in a variety of contexts.
1108 /// The most basic pattern in which `collect()` is used is to turn one
1109 /// collection into another. You take a collection, call [`iter`] on it,
1110 /// do a bunch of transformations, and then `collect()` at the end.
1112 /// One of the keys to `collect()`'s power is that many things you might
1113 /// not think of as 'collections' actually are. For example, a [`String`]
1114 /// is a collection of [`char`]s. And a collection of
1115 /// [`Result<T, E>`][`Result`] can be thought of as single
1116 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1118 /// Because `collect()` is so general, it can cause problems with type
1119 /// inference. As such, `collect()` is one of the few times you'll see
1120 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1121 /// helps the inference algorithm understand specifically which collection
1122 /// you're trying to collect into.
1129 /// let a = [1, 2, 3];
1131 /// let doubled: Vec<i32> = a.iter()
1132 /// .map(|&x| x * 2)
1135 /// assert_eq!(vec![2, 4, 6], doubled);
1138 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1139 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1141 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1144 /// use std::collections::VecDeque;
1146 /// let a = [1, 2, 3];
1148 /// let doubled: VecDeque<i32> = a.iter()
1149 /// .map(|&x| x * 2)
1152 /// assert_eq!(2, doubled[0]);
1153 /// assert_eq!(4, doubled[1]);
1154 /// assert_eq!(6, doubled[2]);
1157 /// Using the 'turbofish' instead of annotating `doubled`:
1160 /// let a = [1, 2, 3];
1162 /// let doubled = a.iter()
1163 /// .map(|&x| x * 2)
1164 /// .collect::<Vec<i32>>();
1166 /// assert_eq!(vec![2, 4, 6], doubled);
1169 /// Because `collect()` cares about what you're collecting into, you can
1170 /// still use a partial type hint, `_`, with the turbofish:
1173 /// let a = [1, 2, 3];
1175 /// let doubled = a.iter()
1176 /// .map(|&x| x * 2)
1177 /// .collect::<Vec<_>>();
1179 /// assert_eq!(vec![2, 4, 6], doubled);
1182 /// Using `collect()` to make a [`String`]:
1185 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1187 /// let hello: String = chars.iter()
1188 /// .map(|&x| x as u8)
1189 /// .map(|x| (x + 1) as char)
1192 /// assert_eq!("hello", hello);
1195 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1196 /// see if any of them failed:
1199 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1201 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1203 /// // gives us the first error
1204 /// assert_eq!(Err("nope"), result);
1206 /// let results = [Ok(1), Ok(3)];
1208 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1210 /// // gives us the list of answers
1211 /// assert_eq!(Ok(vec![1, 3]), result);
1214 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1215 /// [`String`]: ../../std/string/struct.String.html
1216 /// [`char`]: ../../std/primitive.char.html
1217 /// [`Result`]: ../../std/result/enum.Result.html
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1221 FromIterator::from_iter(self)
1224 /// Consumes an iterator, creating two collections from it.
1226 /// The predicate passed to `partition()` can return `true`, or `false`.
1227 /// `partition()` returns a pair, all of the elements for which it returned
1228 /// `true`, and all of the elements for which it returned `false`.
1235 /// let a = [1, 2, 3];
1237 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1238 /// .partition(|&n| n % 2 == 0);
1240 /// assert_eq!(even, vec![2]);
1241 /// assert_eq!(odd, vec![1, 3]);
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 fn partition<B, F>(self, mut f: F) -> (B, B) where
1246 B: Default + Extend<Self::Item>,
1247 F: FnMut(&Self::Item) -> bool
1249 let mut left: B = Default::default();
1250 let mut right: B = Default::default();
1254 left.extend(Some(x))
1256 right.extend(Some(x))
1263 /// An iterator adaptor that applies a function, producing a single, final value.
1265 /// `fold()` takes two arguments: an initial value, and a closure with two
1266 /// arguments: an 'accumulator', and an element. The closure returns the value that
1267 /// the accumulator should have for the next iteration.
1269 /// The initial value is the value the accumulator will have on the first
1272 /// After applying this closure to every element of the iterator, `fold()`
1273 /// returns the accumulator.
1275 /// This operation is sometimes called 'reduce' or 'inject'.
1277 /// Folding is useful whenever you have a collection of something, and want
1278 /// to produce a single value from it.
1285 /// let a = [1, 2, 3];
1287 /// // the sum of all of the elements of a
1288 /// let sum = a.iter()
1289 /// .fold(0, |acc, &x| acc + x);
1291 /// assert_eq!(sum, 6);
1294 /// Let's walk through each step of the iteration here:
1296 /// | element | acc | x | result |
1297 /// |---------|-----|---|--------|
1299 /// | 1 | 0 | 1 | 1 |
1300 /// | 2 | 1 | 2 | 3 |
1301 /// | 3 | 3 | 3 | 6 |
1303 /// And so, our final result, `6`.
1305 /// It's common for people who haven't used iterators a lot to
1306 /// use a `for` loop with a list of things to build up a result. Those
1307 /// can be turned into `fold()`s:
1309 /// [`for`]: ../../book/first-edition/loops.html#for
1312 /// let numbers = [1, 2, 3, 4, 5];
1314 /// let mut result = 0;
1317 /// for i in &numbers {
1318 /// result = result + i;
1322 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1324 /// // they're the same
1325 /// assert_eq!(result, result2);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 fn fold<B, F>(self, init: B, mut f: F) -> B where
1330 Self: Sized, F: FnMut(B, Self::Item) -> B,
1332 let mut accum = init;
1334 accum = f(accum, x);
1339 /// Tests if every element of the iterator matches a predicate.
1341 /// `all()` takes a closure that returns `true` or `false`. It applies
1342 /// this closure to each element of the iterator, and if they all return
1343 /// `true`, then so does `all()`. If any of them return `false`, it
1344 /// returns `false`.
1346 /// `all()` is short-circuiting; in other words, it will stop processing
1347 /// as soon as it finds a `false`, given that no matter what else happens,
1348 /// the result will also be `false`.
1350 /// An empty iterator returns `true`.
1357 /// let a = [1, 2, 3];
1359 /// assert!(a.iter().all(|&x| x > 0));
1361 /// assert!(!a.iter().all(|&x| x > 2));
1364 /// Stopping at the first `false`:
1367 /// let a = [1, 2, 3];
1369 /// let mut iter = a.iter();
1371 /// assert!(!iter.all(|&x| x != 2));
1373 /// // we can still use `iter`, as there are more elements.
1374 /// assert_eq!(iter.next(), Some(&3));
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 fn all<F>(&mut self, mut f: F) -> bool where
1379 Self: Sized, F: FnMut(Self::Item) -> bool
1389 /// Tests if any element of the iterator matches a predicate.
1391 /// `any()` takes a closure that returns `true` or `false`. It applies
1392 /// this closure to each element of the iterator, and if any of them return
1393 /// `true`, then so does `any()`. If they all return `false`, it
1394 /// returns `false`.
1396 /// `any()` is short-circuiting; in other words, it will stop processing
1397 /// as soon as it finds a `true`, given that no matter what else happens,
1398 /// the result will also be `true`.
1400 /// An empty iterator returns `false`.
1407 /// let a = [1, 2, 3];
1409 /// assert!(a.iter().any(|&x| x > 0));
1411 /// assert!(!a.iter().any(|&x| x > 5));
1414 /// Stopping at the first `true`:
1417 /// let a = [1, 2, 3];
1419 /// let mut iter = a.iter();
1421 /// assert!(iter.any(|&x| x != 2));
1423 /// // we can still use `iter`, as there are more elements.
1424 /// assert_eq!(iter.next(), Some(&2));
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 fn any<F>(&mut self, mut f: F) -> bool where
1430 F: FnMut(Self::Item) -> bool
1440 /// Searches for an element of an iterator that satisfies a predicate.
1442 /// `find()` takes a closure that returns `true` or `false`. It applies
1443 /// this closure to each element of the iterator, and if any of them return
1444 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1445 /// `false`, it returns [`None`].
1447 /// `find()` is short-circuiting; in other words, it will stop processing
1448 /// as soon as the closure returns `true`.
1450 /// Because `find()` takes a reference, and many iterators iterate over
1451 /// references, this leads to a possibly confusing situation where the
1452 /// argument is a double reference. You can see this effect in the
1453 /// examples below, with `&&x`.
1455 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1456 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1463 /// let a = [1, 2, 3];
1465 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1467 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1470 /// Stopping at the first `true`:
1473 /// let a = [1, 2, 3];
1475 /// let mut iter = a.iter();
1477 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1479 /// // we can still use `iter`, as there are more elements.
1480 /// assert_eq!(iter.next(), Some(&3));
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1486 P: FnMut(&Self::Item) -> bool,
1489 if predicate(&x) { return Some(x) }
1494 /// Searches for an element in an iterator, returning its index.
1496 /// `position()` takes a closure that returns `true` or `false`. It applies
1497 /// this closure to each element of the iterator, and if one of them
1498 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1499 /// them return `false`, it returns [`None`].
1501 /// `position()` is short-circuiting; in other words, it will stop
1502 /// processing as soon as it finds a `true`.
1504 /// # Overflow Behavior
1506 /// The method does no guarding against overflows, so if there are more
1507 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1508 /// result or panics. If debug assertions are enabled, a panic is
1513 /// This function might panic if the iterator has more than `usize::MAX`
1514 /// non-matching elements.
1516 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1517 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1518 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1525 /// let a = [1, 2, 3];
1527 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1529 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1532 /// Stopping at the first `true`:
1535 /// let a = [1, 2, 3, 4];
1537 /// let mut iter = a.iter();
1539 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1541 /// // we can still use `iter`, as there are more elements.
1542 /// assert_eq!(iter.next(), Some(&3));
1544 /// // The returned index depends on iterator state
1545 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1552 P: FnMut(Self::Item) -> bool,
1554 // `enumerate` might overflow.
1555 for (i, x) in self.enumerate() {
1563 /// Searches for an element in an iterator from the right, returning its
1566 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1567 /// this closure to each element of the iterator, starting from the end,
1568 /// and if one of them returns `true`, then `rposition()` returns
1569 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1571 /// `rposition()` is short-circuiting; in other words, it will stop
1572 /// processing as soon as it finds a `true`.
1574 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1575 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1582 /// let a = [1, 2, 3];
1584 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1586 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1589 /// Stopping at the first `true`:
1592 /// let a = [1, 2, 3];
1594 /// let mut iter = a.iter();
1596 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1598 /// // we can still use `iter`, as there are more elements.
1599 /// assert_eq!(iter.next(), Some(&1));
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1604 P: FnMut(Self::Item) -> bool,
1605 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1607 let mut i = self.len();
1609 while let Some(v) = self.next_back() {
1610 // No need for an overflow check here, because `ExactSizeIterator`
1611 // implies that the number of elements fits into a `usize`.
1620 /// Returns the maximum element of an iterator.
1622 /// If several elements are equally maximum, the last element is
1623 /// returned. If the iterator is empty, [`None`] is returned.
1625 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1632 /// let a = [1, 2, 3];
1633 /// let b: Vec<u32> = Vec::new();
1635 /// assert_eq!(a.iter().max(), Some(&3));
1636 /// assert_eq!(b.iter().max(), None);
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1644 // switch to y even if it is only equal, to preserve
1646 |_, x, _, y| *x <= *y)
1650 /// Returns the minimum element of an iterator.
1652 /// If several elements are equally minimum, the first element is
1653 /// returned. If the iterator is empty, [`None`] is returned.
1655 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1662 /// let a = [1, 2, 3];
1663 /// let b: Vec<u32> = Vec::new();
1665 /// assert_eq!(a.iter().min(), Some(&1));
1666 /// assert_eq!(b.iter().min(), None);
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1674 // only switch to y if it is strictly smaller, to
1675 // preserve stability.
1676 |_, x, _, y| *x > *y)
1680 /// Returns the element that gives the maximum value from the
1681 /// specified function.
1683 /// If several elements are equally maximum, the last element is
1684 /// returned. If the iterator is empty, [`None`] is returned.
1686 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1691 /// let a = [-3_i32, 0, 1, 5, -10];
1692 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1695 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1696 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1697 where Self: Sized, F: FnMut(&Self::Item) -> B,
1701 // switch to y even if it is only equal, to preserve
1703 |x_p, _, y_p, _| x_p <= y_p)
1707 /// Returns the element that gives the maximum value with respect to the
1708 /// specified comparison function.
1710 /// If several elements are equally maximum, the last element is
1711 /// returned. If the iterator is empty, [`None`] is returned.
1713 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1718 /// let a = [-3_i32, 0, 1, 5, -10];
1719 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1722 #[stable(feature = "iter_max_by", since = "1.15.0")]
1723 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1724 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1728 // switch to y even if it is only equal, to preserve
1730 |_, x, _, y| Ordering::Greater != compare(x, y))
1734 /// Returns the element that gives the minimum value from the
1735 /// specified function.
1737 /// If several elements are equally minimum, the first element is
1738 /// returned. If the iterator is empty, [`None`] is returned.
1740 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1745 /// let a = [-3_i32, 0, 1, 5, -10];
1746 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1748 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1749 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1750 where Self: Sized, F: FnMut(&Self::Item) -> B,
1754 // only switch to y if it is strictly smaller, to
1755 // preserve stability.
1756 |x_p, _, y_p, _| x_p > y_p)
1760 /// Returns the element that gives the minimum value with respect to the
1761 /// specified comparison function.
1763 /// If several elements are equally minimum, the first element is
1764 /// returned. If the iterator is empty, [`None`] is returned.
1766 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1771 /// let a = [-3_i32, 0, 1, 5, -10];
1772 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1775 #[stable(feature = "iter_min_by", since = "1.15.0")]
1776 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
1777 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1781 // switch to y even if it is strictly smaller, to
1782 // preserve stability.
1783 |_, x, _, y| Ordering::Greater == compare(x, y))
1788 /// Reverses an iterator's direction.
1790 /// Usually, iterators iterate from left to right. After using `rev()`,
1791 /// an iterator will instead iterate from right to left.
1793 /// This is only possible if the iterator has an end, so `rev()` only
1794 /// works on [`DoubleEndedIterator`]s.
1796 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1801 /// let a = [1, 2, 3];
1803 /// let mut iter = a.iter().rev();
1805 /// assert_eq!(iter.next(), Some(&3));
1806 /// assert_eq!(iter.next(), Some(&2));
1807 /// assert_eq!(iter.next(), Some(&1));
1809 /// assert_eq!(iter.next(), None);
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1817 /// Converts an iterator of pairs into a pair of containers.
1819 /// `unzip()` consumes an entire iterator of pairs, producing two
1820 /// collections: one from the left elements of the pairs, and one
1821 /// from the right elements.
1823 /// This function is, in some sense, the opposite of [`zip`].
1825 /// [`zip`]: #method.zip
1832 /// let a = [(1, 2), (3, 4)];
1834 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1836 /// assert_eq!(left, [1, 3]);
1837 /// assert_eq!(right, [2, 4]);
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1841 FromA: Default + Extend<A>,
1842 FromB: Default + Extend<B>,
1843 Self: Sized + Iterator<Item=(A, B)>,
1845 let mut ts: FromA = Default::default();
1846 let mut us: FromB = Default::default();
1848 for (t, u) in self {
1856 /// Creates an iterator which [`clone`]s all of its elements.
1858 /// This is useful when you have an iterator over `&T`, but you need an
1859 /// iterator over `T`.
1861 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
1868 /// let a = [1, 2, 3];
1870 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1872 /// // cloned is the same as .map(|&x| x), for integers
1873 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1875 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1876 /// assert_eq!(v_map, vec![1, 2, 3]);
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1880 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1885 /// Repeats an iterator endlessly.
1887 /// Instead of stopping at [`None`], the iterator will instead start again,
1888 /// from the beginning. After iterating again, it will start at the
1889 /// beginning again. And again. And again. Forever.
1891 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1898 /// let a = [1, 2, 3];
1900 /// let mut it = a.iter().cycle();
1902 /// assert_eq!(it.next(), Some(&1));
1903 /// assert_eq!(it.next(), Some(&2));
1904 /// assert_eq!(it.next(), Some(&3));
1905 /// assert_eq!(it.next(), Some(&1));
1906 /// assert_eq!(it.next(), Some(&2));
1907 /// assert_eq!(it.next(), Some(&3));
1908 /// assert_eq!(it.next(), Some(&1));
1910 #[stable(feature = "rust1", since = "1.0.0")]
1912 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1913 Cycle{orig: self.clone(), iter: self}
1916 /// Sums the elements of an iterator.
1918 /// Takes each element, adds them together, and returns the result.
1920 /// An empty iterator returns the zero value of the type.
1924 /// When calling `sum()` and a primitive integer type is being returned, this
1925 /// method will panic if the computation overflows and debug assertions are
1933 /// let a = [1, 2, 3];
1934 /// let sum: i32 = a.iter().sum();
1936 /// assert_eq!(sum, 6);
1938 #[stable(feature = "iter_arith", since = "1.11.0")]
1939 fn sum<S>(self) -> S
1946 /// Iterates over the entire iterator, multiplying all the elements
1948 /// An empty iterator returns the one value of the type.
1952 /// When calling `product()` and a primitive integer type is being returned,
1953 /// method will panic if the computation overflows and debug assertions are
1959 /// fn factorial(n: u32) -> u32 {
1960 /// (1..).take_while(|&i| i <= n).product()
1962 /// assert_eq!(factorial(0), 1);
1963 /// assert_eq!(factorial(1), 1);
1964 /// assert_eq!(factorial(5), 120);
1966 #[stable(feature = "iter_arith", since = "1.11.0")]
1967 fn product<P>(self) -> P
1969 P: Product<Self::Item>,
1971 Product::product(self)
1974 /// Lexicographically compares the elements of this `Iterator` with those
1976 #[stable(feature = "iter_order", since = "1.5.0")]
1977 fn cmp<I>(mut self, other: I) -> Ordering where
1978 I: IntoIterator<Item = Self::Item>,
1982 let mut other = other.into_iter();
1985 match (self.next(), other.next()) {
1986 (None, None) => return Ordering::Equal,
1987 (None, _ ) => return Ordering::Less,
1988 (_ , None) => return Ordering::Greater,
1989 (Some(x), Some(y)) => match x.cmp(&y) {
1990 Ordering::Equal => (),
1991 non_eq => return non_eq,
1997 /// Lexicographically compares the elements of this `Iterator` with those
1999 #[stable(feature = "iter_order", since = "1.5.0")]
2000 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2002 Self::Item: PartialOrd<I::Item>,
2005 let mut other = other.into_iter();
2008 match (self.next(), other.next()) {
2009 (None, None) => return Some(Ordering::Equal),
2010 (None, _ ) => return Some(Ordering::Less),
2011 (_ , None) => return Some(Ordering::Greater),
2012 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2013 Some(Ordering::Equal) => (),
2014 non_eq => return non_eq,
2020 /// Determines if the elements of this `Iterator` are equal to those of
2022 #[stable(feature = "iter_order", since = "1.5.0")]
2023 fn eq<I>(mut self, other: I) -> bool where
2025 Self::Item: PartialEq<I::Item>,
2028 let mut other = other.into_iter();
2031 match (self.next(), other.next()) {
2032 (None, None) => return true,
2033 (None, _) | (_, None) => return false,
2034 (Some(x), Some(y)) => if x != y { return false },
2039 /// Determines if the elements of this `Iterator` are unequal to those of
2041 #[stable(feature = "iter_order", since = "1.5.0")]
2042 fn ne<I>(mut self, other: I) -> bool where
2044 Self::Item: PartialEq<I::Item>,
2047 let mut other = other.into_iter();
2050 match (self.next(), other.next()) {
2051 (None, None) => return false,
2052 (None, _) | (_, None) => return true,
2053 (Some(x), Some(y)) => if x.ne(&y) { return true },
2058 /// Determines if the elements of this `Iterator` are lexicographically
2059 /// less than those of another.
2060 #[stable(feature = "iter_order", since = "1.5.0")]
2061 fn lt<I>(mut self, other: I) -> bool where
2063 Self::Item: PartialOrd<I::Item>,
2066 let mut other = other.into_iter();
2069 match (self.next(), other.next()) {
2070 (None, None) => return false,
2071 (None, _ ) => return true,
2072 (_ , None) => return false,
2073 (Some(x), Some(y)) => {
2074 match x.partial_cmp(&y) {
2075 Some(Ordering::Less) => return true,
2076 Some(Ordering::Equal) => {}
2077 Some(Ordering::Greater) => return false,
2078 None => return false,
2085 /// Determines if the elements of this `Iterator` are lexicographically
2086 /// less or equal to those of another.
2087 #[stable(feature = "iter_order", since = "1.5.0")]
2088 fn le<I>(mut self, other: I) -> bool where
2090 Self::Item: PartialOrd<I::Item>,
2093 let mut other = other.into_iter();
2096 match (self.next(), other.next()) {
2097 (None, None) => return true,
2098 (None, _ ) => return true,
2099 (_ , None) => return false,
2100 (Some(x), Some(y)) => {
2101 match x.partial_cmp(&y) {
2102 Some(Ordering::Less) => return true,
2103 Some(Ordering::Equal) => {}
2104 Some(Ordering::Greater) => return false,
2105 None => return false,
2112 /// Determines if the elements of this `Iterator` are lexicographically
2113 /// greater than those of another.
2114 #[stable(feature = "iter_order", since = "1.5.0")]
2115 fn gt<I>(mut self, other: I) -> bool where
2117 Self::Item: PartialOrd<I::Item>,
2120 let mut other = other.into_iter();
2123 match (self.next(), other.next()) {
2124 (None, None) => return false,
2125 (None, _ ) => return false,
2126 (_ , None) => return true,
2127 (Some(x), Some(y)) => {
2128 match x.partial_cmp(&y) {
2129 Some(Ordering::Less) => return false,
2130 Some(Ordering::Equal) => {}
2131 Some(Ordering::Greater) => return true,
2132 None => return false,
2139 /// Determines if the elements of this `Iterator` are lexicographically
2140 /// greater than or equal to those of another.
2141 #[stable(feature = "iter_order", since = "1.5.0")]
2142 fn ge<I>(mut self, other: I) -> bool where
2144 Self::Item: PartialOrd<I::Item>,
2147 let mut other = other.into_iter();
2150 match (self.next(), other.next()) {
2151 (None, None) => return true,
2152 (None, _ ) => return false,
2153 (_ , None) => return true,
2154 (Some(x), Some(y)) => {
2155 match x.partial_cmp(&y) {
2156 Some(Ordering::Less) => return false,
2157 Some(Ordering::Equal) => {}
2158 Some(Ordering::Greater) => return true,
2159 None => return false,
2167 /// Select an element from an iterator based on the given "projection"
2168 /// and "comparison" function.
2170 /// This is an idiosyncratic helper to try to factor out the
2171 /// commonalities of {max,min}{,_by}. In particular, this avoids
2172 /// having to implement optimizations several times.
2174 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2176 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2178 FProj: FnMut(&I::Item) -> B,
2179 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2181 // start with the first element as our selection. This avoids
2182 // having to use `Option`s inside the loop, translating to a
2183 // sizeable performance gain (6x in one case).
2184 it.next().map(|mut sel| {
2185 let mut sel_p = f_proj(&sel);
2188 let x_p = f_proj(&x);
2189 if f_cmp(&sel_p, &sel, &x_p, &x) {
2198 #[stable(feature = "rust1", since = "1.0.0")]
2199 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2200 type Item = I::Item;
2201 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2202 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2203 fn nth(&mut self, n: usize) -> Option<Self::Item> {