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, StepBy, 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 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
133 /// // and the maximum possible lower bound
136 /// assert_eq!((usize::max_value(), None), iter.size_hint());
139 #[stable(feature = "rust1", since = "1.0.0")]
140 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
142 /// Consumes the iterator, counting the number of iterations and returning it.
144 /// This method will evaluate the iterator until its [`next`] returns
145 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
146 /// times it called [`next`].
148 /// [`next`]: #tymethod.next
149 /// [`None`]: ../../std/option/enum.Option.html#variant.None
151 /// # Overflow Behavior
153 /// The method does no guarding against overflows, so counting elements of
154 /// an iterator with more than [`usize::MAX`] elements either produces the
155 /// wrong result or panics. If debug assertions are enabled, a panic is
160 /// This function might panic if the iterator has more than [`usize::MAX`]
163 /// [`usize::MAX`]: ../../std/isize/constant.MAX.html
170 /// let a = [1, 2, 3];
171 /// assert_eq!(a.iter().count(), 3);
173 /// let a = [1, 2, 3, 4, 5];
174 /// assert_eq!(a.iter().count(), 5);
177 #[rustc_inherit_overflow_checks]
178 #[stable(feature = "rust1", since = "1.0.0")]
179 fn count(self) -> usize where Self: Sized {
181 self.fold(0, |cnt, _| cnt + 1)
184 /// Consumes the iterator, returning the last element.
186 /// This method will evaluate the iterator until it returns [`None`]. While
187 /// doing so, it keeps track of the current element. After [`None`] is
188 /// returned, `last()` will then return the last element it saw.
190 /// [`None`]: ../../std/option/enum.Option.html#variant.None
197 /// let a = [1, 2, 3];
198 /// assert_eq!(a.iter().last(), Some(&3));
200 /// let a = [1, 2, 3, 4, 5];
201 /// assert_eq!(a.iter().last(), Some(&5));
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn last(self) -> Option<Self::Item> where Self: Sized {
207 for x in self { last = Some(x); }
211 /// Returns the `n`th element of the iterator.
213 /// Like most indexing operations, the count starts from zero, so `nth(0)`
214 /// returns the first value, `nth(1)` the second, and so on.
216 /// Note that all preceding elements, as well as the returned element, will be
217 /// consumed from the iterator. That means that the preceding elements will be
218 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
219 /// will return different elements.
221 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
224 /// [`None`]: ../../std/option/enum.Option.html#variant.None
231 /// let a = [1, 2, 3];
232 /// assert_eq!(a.iter().nth(1), Some(&2));
235 /// Calling `nth()` multiple times doesn't rewind the iterator:
238 /// let a = [1, 2, 3];
240 /// let mut iter = a.iter();
242 /// assert_eq!(iter.nth(1), Some(&2));
243 /// assert_eq!(iter.nth(1), None);
246 /// Returning `None` if there are less than `n + 1` elements:
249 /// let a = [1, 2, 3];
250 /// assert_eq!(a.iter().nth(10), None);
253 #[stable(feature = "rust1", since = "1.0.0")]
254 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
256 if n == 0 { return Some(x) }
262 /// Creates an iterator starting at the same point, but stepping by
263 /// the given amount at each iteration.
265 /// Note that it will always return the first element of the iterator,
266 /// regardless of the step given.
270 /// The method will panic if the given step is `0`.
277 /// #![feature(iterator_step_by)]
278 /// let a = [0, 1, 2, 3, 4, 5];
279 /// let mut iter = a.into_iter().step_by(2);
281 /// assert_eq!(iter.next(), Some(&0));
282 /// assert_eq!(iter.next(), Some(&2));
283 /// assert_eq!(iter.next(), Some(&4));
284 /// assert_eq!(iter.next(), None);
287 #[unstable(feature = "iterator_step_by",
288 reason = "unstable replacement of Range::step_by",
290 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
292 StepBy{iter: self, step: step - 1, first_take: true}
295 /// Takes two iterators and creates a new iterator over both in sequence.
297 /// `chain()` will return a new iterator which will first iterate over
298 /// values from the first iterator and then over values from the second
301 /// In other words, it links two iterators together, in a chain. 🔗
308 /// let a1 = [1, 2, 3];
309 /// let a2 = [4, 5, 6];
311 /// let mut iter = a1.iter().chain(a2.iter());
313 /// assert_eq!(iter.next(), Some(&1));
314 /// assert_eq!(iter.next(), Some(&2));
315 /// assert_eq!(iter.next(), Some(&3));
316 /// assert_eq!(iter.next(), Some(&4));
317 /// assert_eq!(iter.next(), Some(&5));
318 /// assert_eq!(iter.next(), Some(&6));
319 /// assert_eq!(iter.next(), None);
322 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
323 /// anything that can be converted into an [`Iterator`], not just an
324 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
325 /// [`IntoIterator`], and so can be passed to `chain()` directly:
327 /// [`IntoIterator`]: trait.IntoIterator.html
328 /// [`Iterator`]: trait.Iterator.html
331 /// let s1 = &[1, 2, 3];
332 /// let s2 = &[4, 5, 6];
334 /// let mut iter = s1.iter().chain(s2);
336 /// assert_eq!(iter.next(), Some(&1));
337 /// assert_eq!(iter.next(), Some(&2));
338 /// assert_eq!(iter.next(), Some(&3));
339 /// assert_eq!(iter.next(), Some(&4));
340 /// assert_eq!(iter.next(), Some(&5));
341 /// assert_eq!(iter.next(), Some(&6));
342 /// assert_eq!(iter.next(), None);
345 #[stable(feature = "rust1", since = "1.0.0")]
346 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
347 Self: Sized, U: IntoIterator<Item=Self::Item>,
349 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
352 /// 'Zips up' two iterators into a single iterator of pairs.
354 /// `zip()` returns a new iterator that will iterate over two other
355 /// iterators, returning a tuple where the first element comes from the
356 /// first iterator, and the second element comes from the second iterator.
358 /// In other words, it zips two iterators together, into a single one.
360 /// When either iterator returns [`None`], all further calls to [`next`]
361 /// will return [`None`].
368 /// let a1 = [1, 2, 3];
369 /// let a2 = [4, 5, 6];
371 /// let mut iter = a1.iter().zip(a2.iter());
373 /// assert_eq!(iter.next(), Some((&1, &4)));
374 /// assert_eq!(iter.next(), Some((&2, &5)));
375 /// assert_eq!(iter.next(), Some((&3, &6)));
376 /// assert_eq!(iter.next(), None);
379 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
380 /// anything that can be converted into an [`Iterator`], not just an
381 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
382 /// [`IntoIterator`], and so can be passed to `zip()` directly:
384 /// [`IntoIterator`]: trait.IntoIterator.html
385 /// [`Iterator`]: trait.Iterator.html
388 /// let s1 = &[1, 2, 3];
389 /// let s2 = &[4, 5, 6];
391 /// let mut iter = s1.iter().zip(s2);
393 /// assert_eq!(iter.next(), Some((&1, &4)));
394 /// assert_eq!(iter.next(), Some((&2, &5)));
395 /// assert_eq!(iter.next(), Some((&3, &6)));
396 /// assert_eq!(iter.next(), None);
399 /// `zip()` is often used to zip an infinite iterator to a finite one.
400 /// This works because the finite iterator will eventually return [`None`],
401 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
404 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
406 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
408 /// assert_eq!((0, 'f'), enumerate[0]);
409 /// assert_eq!((0, 'f'), zipper[0]);
411 /// assert_eq!((1, 'o'), enumerate[1]);
412 /// assert_eq!((1, 'o'), zipper[1]);
414 /// assert_eq!((2, 'o'), enumerate[2]);
415 /// assert_eq!((2, 'o'), zipper[2]);
418 /// [`enumerate`]: trait.Iterator.html#method.enumerate
419 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
420 /// [`None`]: ../../std/option/enum.Option.html#variant.None
422 #[stable(feature = "rust1", since = "1.0.0")]
423 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
424 Self: Sized, U: IntoIterator
426 Zip::new(self, other.into_iter())
429 /// Takes a closure and creates an iterator which calls that closure on each
432 /// `map()` transforms one iterator into another, by means of its argument:
433 /// something that implements `FnMut`. It produces a new iterator which
434 /// calls this closure on each element of the original iterator.
436 /// If you are good at thinking in types, you can think of `map()` like this:
437 /// If you have an iterator that gives you elements of some type `A`, and
438 /// you want an iterator of some other type `B`, you can use `map()`,
439 /// passing a closure that takes an `A` and returns a `B`.
441 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
442 /// lazy, it is best used when you're already working with other iterators.
443 /// If you're doing some sort of looping for a side effect, it's considered
444 /// more idiomatic to use [`for`] than `map()`.
446 /// [`for`]: ../../book/first-edition/loops.html#for
453 /// let a = [1, 2, 3];
455 /// let mut iter = a.into_iter().map(|x| 2 * x);
457 /// assert_eq!(iter.next(), Some(2));
458 /// assert_eq!(iter.next(), Some(4));
459 /// assert_eq!(iter.next(), Some(6));
460 /// assert_eq!(iter.next(), None);
463 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
466 /// # #![allow(unused_must_use)]
467 /// // don't do this:
468 /// (0..5).map(|x| println!("{}", x));
470 /// // it won't even execute, as it is lazy. Rust will warn you about this.
472 /// // Instead, use for:
474 /// println!("{}", x);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 fn map<B, F>(self, f: F) -> Map<Self, F> where
480 Self: Sized, F: FnMut(Self::Item) -> B,
482 Map{iter: self, f: f}
485 /// Calls a closure on each element of an iterator.
487 /// This is equivalent to using a [`for`] loop on the iterator, although
488 /// `break` and `continue` are not possible from a closure. It's generally
489 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
490 /// when processing items at the end of longer iterator chains. In some
491 /// cases `for_each` may also be faster than a loop, because it will use
492 /// internal iteration on adaptors like `Chain`.
494 /// [`for`]: ../../book/first-edition/loops.html#for
501 /// #![feature(iterator_for_each)]
503 /// use std::sync::mpsc::channel;
505 /// let (tx, rx) = channel();
506 /// (0..5).map(|x| x * 2 + 1)
507 /// .for_each(move |x| tx.send(x).unwrap());
509 /// let v: Vec<_> = rx.iter().collect();
510 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
513 /// For such a small example, a `for` loop may be cleaner, but `for_each`
514 /// might be preferable to keep a functional style with longer iterators:
517 /// #![feature(iterator_for_each)]
519 /// (0..5).flat_map(|x| x * 100 .. x * 110)
521 /// .filter(|&(i, x)| (i + x) % 3 == 0)
522 /// .for_each(|(i, x)| println!("{}:{}", i, x));
525 #[unstable(feature = "iterator_for_each", issue = "42986")]
526 fn for_each<F>(self, mut f: F) where
527 Self: Sized, F: FnMut(Self::Item),
529 self.fold((), move |(), item| f(item));
532 /// Creates an iterator which uses a closure to determine if an element
533 /// should be yielded.
535 /// The closure must return `true` or `false`. `filter()` creates an
536 /// iterator which calls this closure on each element. If the closure
537 /// returns `true`, then the element is returned. If the closure returns
538 /// `false`, it will try again, and call the closure on the next element,
539 /// seeing if it passes the test.
546 /// let a = [0i32, 1, 2];
548 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
550 /// assert_eq!(iter.next(), Some(&1));
551 /// assert_eq!(iter.next(), Some(&2));
552 /// assert_eq!(iter.next(), None);
555 /// Because the closure passed to `filter()` takes a reference, and many
556 /// iterators iterate over references, this leads to a possibly confusing
557 /// situation, where the type of the closure is a double reference:
560 /// let a = [0, 1, 2];
562 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
564 /// assert_eq!(iter.next(), Some(&2));
565 /// assert_eq!(iter.next(), None);
568 /// It's common to instead use destructuring on the argument to strip away
572 /// let a = [0, 1, 2];
574 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
576 /// assert_eq!(iter.next(), Some(&2));
577 /// assert_eq!(iter.next(), None);
583 /// let a = [0, 1, 2];
585 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
587 /// assert_eq!(iter.next(), Some(&2));
588 /// assert_eq!(iter.next(), None);
593 #[stable(feature = "rust1", since = "1.0.0")]
594 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
595 Self: Sized, P: FnMut(&Self::Item) -> bool,
597 Filter{iter: self, predicate: predicate}
600 /// Creates an iterator that both filters and maps.
602 /// The closure must return an [`Option<T>`]. `filter_map` creates an
603 /// iterator which calls this closure on each element. If the closure
604 /// returns [`Some(element)`][`Some`], then that element is returned. If the
605 /// closure returns [`None`], it will try again, and call the closure on the
606 /// next element, seeing if it will return [`Some`].
608 /// Why `filter_map` and not just [`filter`].[`map`]? The key is in this
611 /// [`filter`]: #method.filter
612 /// [`map`]: #method.map
614 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
616 /// In other words, it removes the [`Option<T>`] layer automatically. If your
617 /// mapping is already returning an [`Option<T>`] and you want to skip over
618 /// [`None`]s, then `filter_map` is much, much nicer to use.
625 /// let a = ["1", "2", "lol"];
627 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
629 /// assert_eq!(iter.next(), Some(1));
630 /// assert_eq!(iter.next(), Some(2));
631 /// assert_eq!(iter.next(), None);
634 /// Here's the same example, but with [`filter`] and [`map`]:
637 /// let a = ["1", "2", "lol"];
639 /// let mut iter = a.iter()
640 /// .map(|s| s.parse())
641 /// .filter(|s| s.is_ok())
642 /// .map(|s| s.unwrap());
644 /// assert_eq!(iter.next(), Some(1));
645 /// assert_eq!(iter.next(), Some(2));
646 /// assert_eq!(iter.next(), None);
649 /// [`Option<T>`]: ../../std/option/enum.Option.html
650 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
651 /// [`None`]: ../../std/option/enum.Option.html#variant.None
653 #[stable(feature = "rust1", since = "1.0.0")]
654 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
655 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
657 FilterMap { iter: self, f: f }
660 /// Creates an iterator which gives the current iteration count as well as
663 /// The iterator returned yields pairs `(i, val)`, where `i` is the
664 /// current index of iteration and `val` is the value returned by the
667 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
668 /// different sized integer, the [`zip`] function provides similar
671 /// # Overflow Behavior
673 /// The method does no guarding against overflows, so enumerating more than
674 /// [`usize::MAX`] elements either produces the wrong result or panics. If
675 /// debug assertions are enabled, a panic is guaranteed.
679 /// The returned iterator might panic if the to-be-returned index would
680 /// overflow a [`usize`].
682 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
683 /// [`usize`]: ../../std/primitive.usize.html
684 /// [`zip`]: #method.zip
689 /// let a = ['a', 'b', 'c'];
691 /// let mut iter = a.iter().enumerate();
693 /// assert_eq!(iter.next(), Some((0, &'a')));
694 /// assert_eq!(iter.next(), Some((1, &'b')));
695 /// assert_eq!(iter.next(), Some((2, &'c')));
696 /// assert_eq!(iter.next(), None);
699 #[stable(feature = "rust1", since = "1.0.0")]
700 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
701 Enumerate { iter: self, count: 0 }
704 /// Creates an iterator which can use `peek` to look at the next element of
705 /// the iterator without consuming it.
707 /// Adds a [`peek`] method to an iterator. See its documentation for
708 /// more information.
710 /// Note that the underlying iterator is still advanced when [`peek`] is
711 /// called for the first time: In order to retrieve the next element,
712 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
713 /// anything other than fetching the next value) of the [`next`] method
716 /// [`peek`]: struct.Peekable.html#method.peek
717 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
724 /// let xs = [1, 2, 3];
726 /// let mut iter = xs.iter().peekable();
728 /// // peek() lets us see into the future
729 /// assert_eq!(iter.peek(), Some(&&1));
730 /// assert_eq!(iter.next(), Some(&1));
732 /// assert_eq!(iter.next(), Some(&2));
734 /// // we can peek() multiple times, the iterator won't advance
735 /// assert_eq!(iter.peek(), Some(&&3));
736 /// assert_eq!(iter.peek(), Some(&&3));
738 /// assert_eq!(iter.next(), Some(&3));
740 /// // after the iterator is finished, so is peek()
741 /// assert_eq!(iter.peek(), None);
742 /// assert_eq!(iter.next(), None);
745 #[stable(feature = "rust1", since = "1.0.0")]
746 fn peekable(self) -> Peekable<Self> where Self: Sized {
747 Peekable{iter: self, peeked: None}
750 /// Creates an iterator that [`skip`]s elements based on a predicate.
752 /// [`skip`]: #method.skip
754 /// `skip_while()` takes a closure as an argument. It will call this
755 /// closure on each element of the iterator, and ignore elements
756 /// until it returns `false`.
758 /// After `false` is returned, `skip_while()`'s job is over, and the
759 /// rest of the elements are yielded.
766 /// let a = [-1i32, 0, 1];
768 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
770 /// assert_eq!(iter.next(), Some(&0));
771 /// assert_eq!(iter.next(), Some(&1));
772 /// assert_eq!(iter.next(), None);
775 /// Because the closure passed to `skip_while()` takes a reference, and many
776 /// iterators iterate over references, this leads to a possibly confusing
777 /// situation, where the type of the closure is a double reference:
780 /// let a = [-1, 0, 1];
782 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
784 /// assert_eq!(iter.next(), Some(&0));
785 /// assert_eq!(iter.next(), Some(&1));
786 /// assert_eq!(iter.next(), None);
789 /// Stopping after an initial `false`:
792 /// let a = [-1, 0, 1, -2];
794 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
796 /// assert_eq!(iter.next(), Some(&0));
797 /// assert_eq!(iter.next(), Some(&1));
799 /// // while this would have been false, since we already got a false,
800 /// // skip_while() isn't used any more
801 /// assert_eq!(iter.next(), Some(&-2));
803 /// assert_eq!(iter.next(), None);
806 #[stable(feature = "rust1", since = "1.0.0")]
807 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
808 Self: Sized, P: FnMut(&Self::Item) -> bool,
810 SkipWhile{iter: self, flag: false, predicate: predicate}
813 /// Creates an iterator that yields elements based on a predicate.
815 /// `take_while()` takes a closure as an argument. It will call this
816 /// closure on each element of the iterator, and yield elements
817 /// while it returns `true`.
819 /// After `false` is returned, `take_while()`'s job is over, and the
820 /// rest of the elements are ignored.
827 /// let a = [-1i32, 0, 1];
829 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
831 /// assert_eq!(iter.next(), Some(&-1));
832 /// assert_eq!(iter.next(), None);
835 /// Because the closure passed to `take_while()` takes a reference, and many
836 /// iterators iterate over references, this leads to a possibly confusing
837 /// situation, where the type of the closure is a double reference:
840 /// let a = [-1, 0, 1];
842 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
844 /// assert_eq!(iter.next(), Some(&-1));
845 /// assert_eq!(iter.next(), None);
848 /// Stopping after an initial `false`:
851 /// let a = [-1, 0, 1, -2];
853 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
855 /// assert_eq!(iter.next(), Some(&-1));
857 /// // We have more elements that are less than zero, but since we already
858 /// // got a false, take_while() isn't used any more
859 /// assert_eq!(iter.next(), None);
862 /// Because `take_while()` needs to look at the value in order to see if it
863 /// should be included or not, consuming iterators will see that it is
867 /// let a = [1, 2, 3, 4];
868 /// let mut iter = a.into_iter();
870 /// let result: Vec<i32> = iter.by_ref()
871 /// .take_while(|n| **n != 3)
875 /// assert_eq!(result, &[1, 2]);
877 /// let result: Vec<i32> = iter.cloned().collect();
879 /// assert_eq!(result, &[4]);
882 /// The `3` is no longer there, because it was consumed in order to see if
883 /// the iteration should stop, but wasn't placed back into the iterator or
884 /// some similar thing.
886 #[stable(feature = "rust1", since = "1.0.0")]
887 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
888 Self: Sized, P: FnMut(&Self::Item) -> bool,
890 TakeWhile{iter: self, flag: false, predicate: predicate}
893 /// Creates an iterator that skips the first `n` elements.
895 /// After they have been consumed, the rest of the elements are yielded.
902 /// let a = [1, 2, 3];
904 /// let mut iter = a.iter().skip(2);
906 /// assert_eq!(iter.next(), Some(&3));
907 /// assert_eq!(iter.next(), None);
910 #[stable(feature = "rust1", since = "1.0.0")]
911 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
912 Skip{iter: self, n: n}
915 /// Creates an iterator that yields its first `n` elements.
922 /// let a = [1, 2, 3];
924 /// let mut iter = a.iter().take(2);
926 /// assert_eq!(iter.next(), Some(&1));
927 /// assert_eq!(iter.next(), Some(&2));
928 /// assert_eq!(iter.next(), None);
931 /// `take()` is often used with an infinite iterator, to make it finite:
934 /// let mut iter = (0..).take(3);
936 /// assert_eq!(iter.next(), Some(0));
937 /// assert_eq!(iter.next(), Some(1));
938 /// assert_eq!(iter.next(), Some(2));
939 /// assert_eq!(iter.next(), None);
942 #[stable(feature = "rust1", since = "1.0.0")]
943 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
944 Take{iter: self, n: n}
947 /// An iterator adaptor similar to [`fold`] that holds internal state and
948 /// produces a new iterator.
950 /// [`fold`]: #method.fold
952 /// `scan()` takes two arguments: an initial value which seeds the internal
953 /// state, and a closure with two arguments, the first being a mutable
954 /// reference to the internal state and the second an iterator element.
955 /// The closure can assign to the internal state to share state between
958 /// On iteration, the closure will be applied to each element of the
959 /// iterator and the return value from the closure, an [`Option`], is
960 /// yielded by the iterator.
962 /// [`Option`]: ../../std/option/enum.Option.html
969 /// let a = [1, 2, 3];
971 /// let mut iter = a.iter().scan(1, |state, &x| {
972 /// // each iteration, we'll multiply the state by the element
973 /// *state = *state * x;
975 /// // the value passed on to the next iteration
979 /// assert_eq!(iter.next(), Some(1));
980 /// assert_eq!(iter.next(), Some(2));
981 /// assert_eq!(iter.next(), Some(6));
982 /// assert_eq!(iter.next(), None);
985 #[stable(feature = "rust1", since = "1.0.0")]
986 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
987 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
989 Scan{iter: self, f: f, state: initial_state}
992 /// Creates an iterator that works like map, but flattens nested structure.
994 /// The [`map`] adapter is very useful, but only when the closure
995 /// argument produces values. If it produces an iterator instead, there's
996 /// an extra layer of indirection. `flat_map()` will remove this extra layer
999 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1000 /// one item for each element, and `flat_map()`'s closure returns an
1001 /// iterator for each element.
1003 /// [`map`]: #method.map
1010 /// let words = ["alpha", "beta", "gamma"];
1012 /// // chars() returns an iterator
1013 /// let merged: String = words.iter()
1014 /// .flat_map(|s| s.chars())
1016 /// assert_eq!(merged, "alphabetagamma");
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1021 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1023 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1026 /// Creates an iterator which ends after the first [`None`].
1028 /// After an iterator returns [`None`], future calls may or may not yield
1029 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1030 /// [`None`] is given, it will always return [`None`] forever.
1032 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1033 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1040 /// // an iterator which alternates between Some and None
1041 /// struct Alternate {
1045 /// impl Iterator for Alternate {
1046 /// type Item = i32;
1048 /// fn next(&mut self) -> Option<i32> {
1049 /// let val = self.state;
1050 /// self.state = self.state + 1;
1052 /// // if it's even, Some(i32), else None
1053 /// if val % 2 == 0 {
1061 /// let mut iter = Alternate { state: 0 };
1063 /// // we can see our iterator going back and forth
1064 /// assert_eq!(iter.next(), Some(0));
1065 /// assert_eq!(iter.next(), None);
1066 /// assert_eq!(iter.next(), Some(2));
1067 /// assert_eq!(iter.next(), None);
1069 /// // however, once we fuse it...
1070 /// let mut iter = iter.fuse();
1072 /// assert_eq!(iter.next(), Some(4));
1073 /// assert_eq!(iter.next(), None);
1075 /// // it will always return None after the first time.
1076 /// assert_eq!(iter.next(), None);
1077 /// assert_eq!(iter.next(), None);
1078 /// assert_eq!(iter.next(), None);
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 fn fuse(self) -> Fuse<Self> where Self: Sized {
1083 Fuse{iter: self, done: false}
1086 /// Do something with each element of an iterator, passing the value on.
1088 /// When using iterators, you'll often chain several of them together.
1089 /// While working on such code, you might want to check out what's
1090 /// happening at various parts in the pipeline. To do that, insert
1091 /// a call to `inspect()`.
1093 /// It's much more common for `inspect()` to be used as a debugging tool
1094 /// than to exist in your final code, but never say never.
1101 /// let a = [1, 4, 2, 3];
1103 /// // this iterator sequence is complex.
1104 /// let sum = a.iter()
1106 /// .filter(|&x| x % 2 == 0)
1107 /// .fold(0, |sum, i| sum + i);
1109 /// println!("{}", sum);
1111 /// // let's add some inspect() calls to investigate what's happening
1112 /// let sum = a.iter()
1114 /// .inspect(|x| println!("about to filter: {}", x))
1115 /// .filter(|&x| x % 2 == 0)
1116 /// .inspect(|x| println!("made it through filter: {}", x))
1117 /// .fold(0, |sum, i| sum + i);
1119 /// println!("{}", sum);
1122 /// This will print:
1125 /// about to filter: 1
1126 /// about to filter: 4
1127 /// made it through filter: 4
1128 /// about to filter: 2
1129 /// made it through filter: 2
1130 /// about to filter: 3
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1136 Self: Sized, F: FnMut(&Self::Item),
1138 Inspect{iter: self, f: f}
1141 /// Borrows an iterator, rather than consuming it.
1143 /// This is useful to allow applying iterator adaptors while still
1144 /// retaining ownership of the original iterator.
1151 /// let a = [1, 2, 3];
1153 /// let iter = a.into_iter();
1155 /// let sum: i32 = iter.take(5)
1156 /// .fold(0, |acc, &i| acc + i );
1158 /// assert_eq!(sum, 6);
1160 /// // if we try to use iter again, it won't work. The following line
1161 /// // gives "error: use of moved value: `iter`
1162 /// // assert_eq!(iter.next(), None);
1164 /// // let's try that again
1165 /// let a = [1, 2, 3];
1167 /// let mut iter = a.into_iter();
1169 /// // instead, we add in a .by_ref()
1170 /// let sum: i32 = iter.by_ref()
1172 /// .fold(0, |acc, &i| acc + i );
1174 /// assert_eq!(sum, 3);
1176 /// // now this is just fine:
1177 /// assert_eq!(iter.next(), Some(&3));
1178 /// assert_eq!(iter.next(), None);
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1183 /// Transforms an iterator into a collection.
1185 /// `collect()` can take anything iterable, and turn it into a relevant
1186 /// collection. This is one of the more powerful methods in the standard
1187 /// library, used in a variety of contexts.
1189 /// The most basic pattern in which `collect()` is used is to turn one
1190 /// collection into another. You take a collection, call [`iter`] on it,
1191 /// do a bunch of transformations, and then `collect()` at the end.
1193 /// One of the keys to `collect()`'s power is that many things you might
1194 /// not think of as 'collections' actually are. For example, a [`String`]
1195 /// is a collection of [`char`]s. And a collection of
1196 /// [`Result<T, E>`][`Result`] can be thought of as single
1197 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1199 /// Because `collect()` is so general, it can cause problems with type
1200 /// inference. As such, `collect()` is one of the few times you'll see
1201 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1202 /// helps the inference algorithm understand specifically which collection
1203 /// you're trying to collect into.
1210 /// let a = [1, 2, 3];
1212 /// let doubled: Vec<i32> = a.iter()
1213 /// .map(|&x| x * 2)
1216 /// assert_eq!(vec![2, 4, 6], doubled);
1219 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1220 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1222 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1225 /// use std::collections::VecDeque;
1227 /// let a = [1, 2, 3];
1229 /// let doubled: VecDeque<i32> = a.iter()
1230 /// .map(|&x| x * 2)
1233 /// assert_eq!(2, doubled[0]);
1234 /// assert_eq!(4, doubled[1]);
1235 /// assert_eq!(6, doubled[2]);
1238 /// Using the 'turbofish' instead of annotating `doubled`:
1241 /// let a = [1, 2, 3];
1243 /// let doubled = a.iter()
1244 /// .map(|&x| x * 2)
1245 /// .collect::<Vec<i32>>();
1247 /// assert_eq!(vec![2, 4, 6], doubled);
1250 /// Because `collect()` cares about what you're collecting into, you can
1251 /// still use a partial type hint, `_`, with the turbofish:
1254 /// let a = [1, 2, 3];
1256 /// let doubled = a.iter()
1257 /// .map(|&x| x * 2)
1258 /// .collect::<Vec<_>>();
1260 /// assert_eq!(vec![2, 4, 6], doubled);
1263 /// Using `collect()` to make a [`String`]:
1266 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1268 /// let hello: String = chars.iter()
1269 /// .map(|&x| x as u8)
1270 /// .map(|x| (x + 1) as char)
1273 /// assert_eq!("hello", hello);
1276 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1277 /// see if any of them failed:
1280 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1282 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1284 /// // gives us the first error
1285 /// assert_eq!(Err("nope"), result);
1287 /// let results = [Ok(1), Ok(3)];
1289 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1291 /// // gives us the list of answers
1292 /// assert_eq!(Ok(vec![1, 3]), result);
1295 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1296 /// [`String`]: ../../std/string/struct.String.html
1297 /// [`char`]: ../../std/primitive.char.html
1298 /// [`Result`]: ../../std/result/enum.Result.html
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1302 FromIterator::from_iter(self)
1305 /// Consumes an iterator, creating two collections from it.
1307 /// The predicate passed to `partition()` can return `true`, or `false`.
1308 /// `partition()` returns a pair, all of the elements for which it returned
1309 /// `true`, and all of the elements for which it returned `false`.
1316 /// let a = [1, 2, 3];
1318 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1319 /// .partition(|&n| n % 2 == 0);
1321 /// assert_eq!(even, vec![2]);
1322 /// assert_eq!(odd, vec![1, 3]);
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 fn partition<B, F>(self, mut f: F) -> (B, B) where
1327 B: Default + Extend<Self::Item>,
1328 F: FnMut(&Self::Item) -> bool
1330 let mut left: B = Default::default();
1331 let mut right: B = Default::default();
1335 left.extend(Some(x))
1337 right.extend(Some(x))
1344 /// An iterator adaptor that applies a function, producing a single, final value.
1346 /// `fold()` takes two arguments: an initial value, and a closure with two
1347 /// arguments: an 'accumulator', and an element. The closure returns the value that
1348 /// the accumulator should have for the next iteration.
1350 /// The initial value is the value the accumulator will have on the first
1353 /// After applying this closure to every element of the iterator, `fold()`
1354 /// returns the accumulator.
1356 /// This operation is sometimes called 'reduce' or 'inject'.
1358 /// Folding is useful whenever you have a collection of something, and want
1359 /// to produce a single value from it.
1366 /// let a = [1, 2, 3];
1368 /// // the sum of all of the elements of a
1369 /// let sum = a.iter()
1370 /// .fold(0, |acc, &x| acc + x);
1372 /// assert_eq!(sum, 6);
1375 /// Let's walk through each step of the iteration here:
1377 /// | element | acc | x | result |
1378 /// |---------|-----|---|--------|
1380 /// | 1 | 0 | 1 | 1 |
1381 /// | 2 | 1 | 2 | 3 |
1382 /// | 3 | 3 | 3 | 6 |
1384 /// And so, our final result, `6`.
1386 /// It's common for people who haven't used iterators a lot to
1387 /// use a `for` loop with a list of things to build up a result. Those
1388 /// can be turned into `fold()`s:
1390 /// [`for`]: ../../book/first-edition/loops.html#for
1393 /// let numbers = [1, 2, 3, 4, 5];
1395 /// let mut result = 0;
1398 /// for i in &numbers {
1399 /// result = result + i;
1403 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1405 /// // they're the same
1406 /// assert_eq!(result, result2);
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 fn fold<B, F>(self, init: B, mut f: F) -> B where
1411 Self: Sized, F: FnMut(B, Self::Item) -> B,
1413 let mut accum = init;
1415 accum = f(accum, x);
1420 /// Tests if every element of the iterator matches a predicate.
1422 /// `all()` takes a closure that returns `true` or `false`. It applies
1423 /// this closure to each element of the iterator, and if they all return
1424 /// `true`, then so does `all()`. If any of them return `false`, it
1425 /// returns `false`.
1427 /// `all()` is short-circuiting; in other words, it will stop processing
1428 /// as soon as it finds a `false`, given that no matter what else happens,
1429 /// the result will also be `false`.
1431 /// An empty iterator returns `true`.
1438 /// let a = [1, 2, 3];
1440 /// assert!(a.iter().all(|&x| x > 0));
1442 /// assert!(!a.iter().all(|&x| x > 2));
1445 /// Stopping at the first `false`:
1448 /// let a = [1, 2, 3];
1450 /// let mut iter = a.iter();
1452 /// assert!(!iter.all(|&x| x != 2));
1454 /// // we can still use `iter`, as there are more elements.
1455 /// assert_eq!(iter.next(), Some(&3));
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 fn all<F>(&mut self, mut f: F) -> bool where
1460 Self: Sized, F: FnMut(Self::Item) -> bool
1470 /// Tests if any element of the iterator matches a predicate.
1472 /// `any()` takes a closure that returns `true` or `false`. It applies
1473 /// this closure to each element of the iterator, and if any of them return
1474 /// `true`, then so does `any()`. If they all return `false`, it
1475 /// returns `false`.
1477 /// `any()` is short-circuiting; in other words, it will stop processing
1478 /// as soon as it finds a `true`, given that no matter what else happens,
1479 /// the result will also be `true`.
1481 /// An empty iterator returns `false`.
1488 /// let a = [1, 2, 3];
1490 /// assert!(a.iter().any(|&x| x > 0));
1492 /// assert!(!a.iter().any(|&x| x > 5));
1495 /// Stopping at the first `true`:
1498 /// let a = [1, 2, 3];
1500 /// let mut iter = a.iter();
1502 /// assert!(iter.any(|&x| x != 2));
1504 /// // we can still use `iter`, as there are more elements.
1505 /// assert_eq!(iter.next(), Some(&2));
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 fn any<F>(&mut self, mut f: F) -> bool where
1511 F: FnMut(Self::Item) -> bool
1521 /// Searches for an element of an iterator that satisfies a predicate.
1523 /// `find()` takes a closure that returns `true` or `false`. It applies
1524 /// this closure to each element of the iterator, and if any of them return
1525 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1526 /// `false`, it returns [`None`].
1528 /// `find()` is short-circuiting; in other words, it will stop processing
1529 /// as soon as the closure returns `true`.
1531 /// Because `find()` takes a reference, and many iterators iterate over
1532 /// references, this leads to a possibly confusing situation where the
1533 /// argument is a double reference. You can see this effect in the
1534 /// examples below, with `&&x`.
1536 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1537 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1544 /// let a = [1, 2, 3];
1546 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1548 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1551 /// Stopping at the first `true`:
1554 /// let a = [1, 2, 3];
1556 /// let mut iter = a.iter();
1558 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1560 /// // we can still use `iter`, as there are more elements.
1561 /// assert_eq!(iter.next(), Some(&3));
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1567 P: FnMut(&Self::Item) -> bool,
1570 if predicate(&x) { return Some(x) }
1575 /// Searches for an element in an iterator, returning its index.
1577 /// `position()` takes a closure that returns `true` or `false`. It applies
1578 /// this closure to each element of the iterator, and if one of them
1579 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1580 /// them return `false`, it returns [`None`].
1582 /// `position()` is short-circuiting; in other words, it will stop
1583 /// processing as soon as it finds a `true`.
1585 /// # Overflow Behavior
1587 /// The method does no guarding against overflows, so if there are more
1588 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1589 /// result or panics. If debug assertions are enabled, a panic is
1594 /// This function might panic if the iterator has more than `usize::MAX`
1595 /// non-matching elements.
1597 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1598 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1599 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1606 /// let a = [1, 2, 3];
1608 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1610 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1613 /// Stopping at the first `true`:
1616 /// let a = [1, 2, 3, 4];
1618 /// let mut iter = a.iter();
1620 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1622 /// // we can still use `iter`, as there are more elements.
1623 /// assert_eq!(iter.next(), Some(&3));
1625 /// // The returned index depends on iterator state
1626 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1633 P: FnMut(Self::Item) -> bool,
1635 // `enumerate` might overflow.
1636 for (i, x) in self.enumerate() {
1644 /// Searches for an element in an iterator from the right, returning its
1647 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1648 /// this closure to each element of the iterator, starting from the end,
1649 /// and if one of them returns `true`, then `rposition()` returns
1650 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1652 /// `rposition()` is short-circuiting; in other words, it will stop
1653 /// processing as soon as it finds a `true`.
1655 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1656 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1663 /// let a = [1, 2, 3];
1665 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1667 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1670 /// Stopping at the first `true`:
1673 /// let a = [1, 2, 3];
1675 /// let mut iter = a.iter();
1677 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1679 /// // we can still use `iter`, as there are more elements.
1680 /// assert_eq!(iter.next(), Some(&1));
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1685 P: FnMut(Self::Item) -> bool,
1686 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1688 let mut i = self.len();
1690 while let Some(v) = self.next_back() {
1691 // No need for an overflow check here, because `ExactSizeIterator`
1692 // implies that the number of elements fits into a `usize`.
1701 /// Returns the maximum element of an iterator.
1703 /// If several elements are equally maximum, the last element is
1704 /// returned. If the iterator is empty, [`None`] is returned.
1706 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1713 /// let a = [1, 2, 3];
1714 /// let b: Vec<u32> = Vec::new();
1716 /// assert_eq!(a.iter().max(), Some(&3));
1717 /// assert_eq!(b.iter().max(), None);
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1725 // switch to y even if it is only equal, to preserve
1727 |_, x, _, y| *x <= *y)
1731 /// Returns the minimum element of an iterator.
1733 /// If several elements are equally minimum, the first element is
1734 /// returned. If the iterator is empty, [`None`] is returned.
1736 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1743 /// let a = [1, 2, 3];
1744 /// let b: Vec<u32> = Vec::new();
1746 /// assert_eq!(a.iter().min(), Some(&1));
1747 /// assert_eq!(b.iter().min(), None);
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1755 // only switch to y if it is strictly smaller, to
1756 // preserve stability.
1757 |_, x, _, y| *x > *y)
1761 /// Returns the element that gives the maximum value from the
1762 /// specified function.
1764 /// If several elements are equally maximum, the last element is
1765 /// returned. If the iterator is empty, [`None`] is returned.
1767 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1772 /// let a = [-3_i32, 0, 1, 5, -10];
1773 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1776 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1777 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1778 where Self: Sized, F: FnMut(&Self::Item) -> B,
1782 // switch to y even if it is only equal, to preserve
1784 |x_p, _, y_p, _| x_p <= y_p)
1788 /// Returns the element that gives the maximum value with respect to the
1789 /// specified comparison function.
1791 /// If several elements are equally maximum, the last element is
1792 /// returned. If the iterator is empty, [`None`] is returned.
1794 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1799 /// let a = [-3_i32, 0, 1, 5, -10];
1800 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1803 #[stable(feature = "iter_max_by", since = "1.15.0")]
1804 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1805 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1809 // switch to y even if it is only equal, to preserve
1811 |_, x, _, y| Ordering::Greater != compare(x, y))
1815 /// Returns the element that gives the minimum value from the
1816 /// specified function.
1818 /// If several elements are equally minimum, the first element is
1819 /// returned. If the iterator is empty, [`None`] is returned.
1821 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1826 /// let a = [-3_i32, 0, 1, 5, -10];
1827 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1829 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1830 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1831 where Self: Sized, F: FnMut(&Self::Item) -> B,
1835 // only switch to y if it is strictly smaller, to
1836 // preserve stability.
1837 |x_p, _, y_p, _| x_p > y_p)
1841 /// Returns the element that gives the minimum value with respect to the
1842 /// specified comparison function.
1844 /// If several elements are equally minimum, the first element is
1845 /// returned. If the iterator is empty, [`None`] is returned.
1847 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1852 /// let a = [-3_i32, 0, 1, 5, -10];
1853 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1856 #[stable(feature = "iter_min_by", since = "1.15.0")]
1857 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
1858 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1862 // switch to y even if it is strictly smaller, to
1863 // preserve stability.
1864 |_, x, _, y| Ordering::Greater == compare(x, y))
1869 /// Reverses an iterator's direction.
1871 /// Usually, iterators iterate from left to right. After using `rev()`,
1872 /// an iterator will instead iterate from right to left.
1874 /// This is only possible if the iterator has an end, so `rev()` only
1875 /// works on [`DoubleEndedIterator`]s.
1877 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1882 /// let a = [1, 2, 3];
1884 /// let mut iter = a.iter().rev();
1886 /// assert_eq!(iter.next(), Some(&3));
1887 /// assert_eq!(iter.next(), Some(&2));
1888 /// assert_eq!(iter.next(), Some(&1));
1890 /// assert_eq!(iter.next(), None);
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1898 /// Converts an iterator of pairs into a pair of containers.
1900 /// `unzip()` consumes an entire iterator of pairs, producing two
1901 /// collections: one from the left elements of the pairs, and one
1902 /// from the right elements.
1904 /// This function is, in some sense, the opposite of [`zip`].
1906 /// [`zip`]: #method.zip
1913 /// let a = [(1, 2), (3, 4)];
1915 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1917 /// assert_eq!(left, [1, 3]);
1918 /// assert_eq!(right, [2, 4]);
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1922 FromA: Default + Extend<A>,
1923 FromB: Default + Extend<B>,
1924 Self: Sized + Iterator<Item=(A, B)>,
1926 let mut ts: FromA = Default::default();
1927 let mut us: FromB = Default::default();
1929 for (t, u) in self {
1937 /// Creates an iterator which [`clone`]s all of its elements.
1939 /// This is useful when you have an iterator over `&T`, but you need an
1940 /// iterator over `T`.
1942 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
1949 /// let a = [1, 2, 3];
1951 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1953 /// // cloned is the same as .map(|&x| x), for integers
1954 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1956 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1957 /// assert_eq!(v_map, vec![1, 2, 3]);
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1961 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1966 /// Repeats an iterator endlessly.
1968 /// Instead of stopping at [`None`], the iterator will instead start again,
1969 /// from the beginning. After iterating again, it will start at the
1970 /// beginning again. And again. And again. Forever.
1972 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1979 /// let a = [1, 2, 3];
1981 /// let mut it = a.iter().cycle();
1983 /// assert_eq!(it.next(), Some(&1));
1984 /// assert_eq!(it.next(), Some(&2));
1985 /// assert_eq!(it.next(), Some(&3));
1986 /// assert_eq!(it.next(), Some(&1));
1987 /// assert_eq!(it.next(), Some(&2));
1988 /// assert_eq!(it.next(), Some(&3));
1989 /// assert_eq!(it.next(), Some(&1));
1991 #[stable(feature = "rust1", since = "1.0.0")]
1993 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1994 Cycle{orig: self.clone(), iter: self}
1997 /// Sums the elements of an iterator.
1999 /// Takes each element, adds them together, and returns the result.
2001 /// An empty iterator returns the zero value of the type.
2005 /// When calling `sum()` and a primitive integer type is being returned, this
2006 /// method will panic if the computation overflows and debug assertions are
2014 /// let a = [1, 2, 3];
2015 /// let sum: i32 = a.iter().sum();
2017 /// assert_eq!(sum, 6);
2019 #[stable(feature = "iter_arith", since = "1.11.0")]
2020 fn sum<S>(self) -> S
2027 /// Iterates over the entire iterator, multiplying all the elements
2029 /// An empty iterator returns the one value of the type.
2033 /// When calling `product()` and a primitive integer type is being returned,
2034 /// method will panic if the computation overflows and debug assertions are
2040 /// fn factorial(n: u32) -> u32 {
2041 /// (1..).take_while(|&i| i <= n).product()
2043 /// assert_eq!(factorial(0), 1);
2044 /// assert_eq!(factorial(1), 1);
2045 /// assert_eq!(factorial(5), 120);
2047 #[stable(feature = "iter_arith", since = "1.11.0")]
2048 fn product<P>(self) -> P
2050 P: Product<Self::Item>,
2052 Product::product(self)
2055 /// Lexicographically compares the elements of this `Iterator` with those
2057 #[stable(feature = "iter_order", since = "1.5.0")]
2058 fn cmp<I>(mut self, other: I) -> Ordering where
2059 I: IntoIterator<Item = Self::Item>,
2063 let mut other = other.into_iter();
2066 match (self.next(), other.next()) {
2067 (None, None) => return Ordering::Equal,
2068 (None, _ ) => return Ordering::Less,
2069 (_ , None) => return Ordering::Greater,
2070 (Some(x), Some(y)) => match x.cmp(&y) {
2071 Ordering::Equal => (),
2072 non_eq => return non_eq,
2078 /// Lexicographically compares the elements of this `Iterator` with those
2080 #[stable(feature = "iter_order", since = "1.5.0")]
2081 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2083 Self::Item: PartialOrd<I::Item>,
2086 let mut other = other.into_iter();
2089 match (self.next(), other.next()) {
2090 (None, None) => return Some(Ordering::Equal),
2091 (None, _ ) => return Some(Ordering::Less),
2092 (_ , None) => return Some(Ordering::Greater),
2093 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2094 Some(Ordering::Equal) => (),
2095 non_eq => return non_eq,
2101 /// Determines if the elements of this `Iterator` are equal to those of
2103 #[stable(feature = "iter_order", since = "1.5.0")]
2104 fn eq<I>(mut self, other: I) -> bool where
2106 Self::Item: PartialEq<I::Item>,
2109 let mut other = other.into_iter();
2112 match (self.next(), other.next()) {
2113 (None, None) => return true,
2114 (None, _) | (_, None) => return false,
2115 (Some(x), Some(y)) => if x != y { return false },
2120 /// Determines if the elements of this `Iterator` are unequal to those of
2122 #[stable(feature = "iter_order", since = "1.5.0")]
2123 fn ne<I>(mut self, other: I) -> bool where
2125 Self::Item: PartialEq<I::Item>,
2128 let mut other = other.into_iter();
2131 match (self.next(), other.next()) {
2132 (None, None) => return false,
2133 (None, _) | (_, None) => return true,
2134 (Some(x), Some(y)) => if x.ne(&y) { return true },
2139 /// Determines if the elements of this `Iterator` are lexicographically
2140 /// less than those of another.
2141 #[stable(feature = "iter_order", since = "1.5.0")]
2142 fn lt<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 false,
2152 (None, _ ) => return true,
2153 (_ , None) => return false,
2154 (Some(x), Some(y)) => {
2155 match x.partial_cmp(&y) {
2156 Some(Ordering::Less) => return true,
2157 Some(Ordering::Equal) => {}
2158 Some(Ordering::Greater) => return false,
2159 None => return false,
2166 /// Determines if the elements of this `Iterator` are lexicographically
2167 /// less or equal to those of another.
2168 #[stable(feature = "iter_order", since = "1.5.0")]
2169 fn le<I>(mut self, other: I) -> bool where
2171 Self::Item: PartialOrd<I::Item>,
2174 let mut other = other.into_iter();
2177 match (self.next(), other.next()) {
2178 (None, None) => return true,
2179 (None, _ ) => return true,
2180 (_ , None) => return false,
2181 (Some(x), Some(y)) => {
2182 match x.partial_cmp(&y) {
2183 Some(Ordering::Less) => return true,
2184 Some(Ordering::Equal) => {}
2185 Some(Ordering::Greater) => return false,
2186 None => return false,
2193 /// Determines if the elements of this `Iterator` are lexicographically
2194 /// greater than those of another.
2195 #[stable(feature = "iter_order", since = "1.5.0")]
2196 fn gt<I>(mut self, other: I) -> bool where
2198 Self::Item: PartialOrd<I::Item>,
2201 let mut other = other.into_iter();
2204 match (self.next(), other.next()) {
2205 (None, None) => return false,
2206 (None, _ ) => return false,
2207 (_ , None) => return true,
2208 (Some(x), Some(y)) => {
2209 match x.partial_cmp(&y) {
2210 Some(Ordering::Less) => return false,
2211 Some(Ordering::Equal) => {}
2212 Some(Ordering::Greater) => return true,
2213 None => return false,
2220 /// Determines if the elements of this `Iterator` are lexicographically
2221 /// greater than or equal to those of another.
2222 #[stable(feature = "iter_order", since = "1.5.0")]
2223 fn ge<I>(mut self, other: I) -> bool where
2225 Self::Item: PartialOrd<I::Item>,
2228 let mut other = other.into_iter();
2231 match (self.next(), other.next()) {
2232 (None, None) => return true,
2233 (None, _ ) => return false,
2234 (_ , None) => return true,
2235 (Some(x), Some(y)) => {
2236 match x.partial_cmp(&y) {
2237 Some(Ordering::Less) => return false,
2238 Some(Ordering::Equal) => {}
2239 Some(Ordering::Greater) => return true,
2240 None => return false,
2248 /// Select an element from an iterator based on the given "projection"
2249 /// and "comparison" function.
2251 /// This is an idiosyncratic helper to try to factor out the
2252 /// commonalities of {max,min}{,_by}. In particular, this avoids
2253 /// having to implement optimizations several times.
2255 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2257 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2259 FProj: FnMut(&I::Item) -> B,
2260 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2262 // start with the first element as our selection. This avoids
2263 // having to use `Option`s inside the loop, translating to a
2264 // sizeable performance gain (6x in one case).
2265 it.next().map(|mut sel| {
2266 let mut sel_p = f_proj(&sel);
2269 let x_p = f_proj(&x);
2270 if f_cmp(&sel_p, &sel, &x_p, &x) {
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2281 type Item = I::Item;
2282 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2283 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2284 fn nth(&mut self, n: usize) -> Option<Self::Item> {