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 range,
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 /// Creates an iterator which uses a closure to determine if an element
486 /// should be yielded.
488 /// The closure must return `true` or `false`. `filter()` creates an
489 /// iterator which calls this closure on each element. If the closure
490 /// returns `true`, then the element is returned. If the closure returns
491 /// `false`, it will try again, and call the closure on the next element,
492 /// seeing if it passes the test.
499 /// let a = [0i32, 1, 2];
501 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
503 /// assert_eq!(iter.next(), Some(&1));
504 /// assert_eq!(iter.next(), Some(&2));
505 /// assert_eq!(iter.next(), None);
508 /// Because the closure passed to `filter()` takes a reference, and many
509 /// iterators iterate over references, this leads to a possibly confusing
510 /// situation, where the type of the closure is a double reference:
513 /// let a = [0, 1, 2];
515 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
517 /// assert_eq!(iter.next(), Some(&2));
518 /// assert_eq!(iter.next(), None);
521 /// It's common to instead use destructuring on the argument to strip away
525 /// let a = [0, 1, 2];
527 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
529 /// assert_eq!(iter.next(), Some(&2));
530 /// assert_eq!(iter.next(), None);
536 /// let a = [0, 1, 2];
538 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
540 /// assert_eq!(iter.next(), Some(&2));
541 /// assert_eq!(iter.next(), None);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 fn filter
<P
>(self, predicate
: P
) -> Filter
<Self, P
> where
548 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
550 Filter{iter: self, predicate: predicate}
553 /// Creates an iterator that both filters and maps.
555 /// The closure must return an [`Option<T>`]. `filter_map` creates an
556 /// iterator which calls this closure on each element. If the closure
557 /// returns [`Some(element)`][`Some`], then that element is returned. If the
558 /// closure returns [`None`], it will try again, and call the closure on the
559 /// next element, seeing if it will return [`Some`].
561 /// Why `filter_map` and not just [`filter`].[`map`]? The key is in this
564 /// [`filter`]: #method.filter
565 /// [`map`]: #method.map
567 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
569 /// In other words, it removes the [`Option<T>`] layer automatically. If your
570 /// mapping is already returning an [`Option<T>`] and you want to skip over
571 /// [`None`]s, then `filter_map` is much, much nicer to use.
578 /// let a = ["1", "2", "lol"];
580 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
582 /// assert_eq!(iter.next(), Some(1));
583 /// assert_eq!(iter.next(), Some(2));
584 /// assert_eq!(iter.next(), None);
587 /// Here's the same example, but with [`filter`] and [`map`]:
590 /// let a = ["1", "2", "lol"];
592 /// let mut iter = a.iter()
593 /// .map(|s| s.parse().ok())
594 /// .filter(|s| s.is_some());
596 /// assert_eq!(iter.next(), Some(Some(1)));
597 /// assert_eq!(iter.next(), Some(Some(2)));
598 /// assert_eq!(iter.next(), None);
601 /// There's an extra layer of [`Some`] in there.
603 /// [`Option<T>`]: ../../std/option/enum.Option.html
604 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
605 /// [`None`]: ../../std/option/enum.Option.html#variant.None
607 #[stable(feature = "rust1", since = "1.0.0")]
608 fn filter_map
<B
, F
>(self, f
: F
) -> FilterMap
<Self, F
> where
609 Self: Sized
, F
: FnMut(Self::Item
) -> Option
<B
>,
611 FilterMap { iter: self, f: f }
614 /// Creates an iterator which gives the current iteration count as well as
617 /// The iterator returned yields pairs `(i, val)`, where `i` is the
618 /// current index of iteration and `val` is the value returned by the
621 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
622 /// different sized integer, the [`zip`] function provides similar
625 /// # Overflow Behavior
627 /// The method does no guarding against overflows, so enumerating more than
628 /// [`usize::MAX`] elements either produces the wrong result or panics. If
629 /// debug assertions are enabled, a panic is guaranteed.
633 /// The returned iterator might panic if the to-be-returned index would
634 /// overflow a [`usize`].
636 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
637 /// [`usize`]: ../../std/primitive.usize.html
638 /// [`zip`]: #method.zip
643 /// let a = ['a', 'b', 'c'];
645 /// let mut iter = a.iter().enumerate();
647 /// assert_eq!(iter.next(), Some((0, &'a')));
648 /// assert_eq!(iter.next(), Some((1, &'b')));
649 /// assert_eq!(iter.next(), Some((2, &'c')));
650 /// assert_eq!(iter.next(), None);
653 #[stable(feature = "rust1", since = "1.0.0")]
654 fn enumerate(self) -> Enumerate
<Self> where Self: Sized
{
655 Enumerate { iter: self, count: 0 }
658 /// Creates an iterator which can use `peek` to look at the next element of
659 /// the iterator without consuming it.
661 /// Adds a [`peek`] method to an iterator. See its documentation for
662 /// more information.
664 /// Note that the underlying iterator is still advanced when [`peek`] is
665 /// called for the first time: In order to retrieve the next element,
666 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
667 /// anything other than fetching the next value) of the [`next`] method
670 /// [`peek`]: struct.Peekable.html#method.peek
671 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
678 /// let xs = [1, 2, 3];
680 /// let mut iter = xs.iter().peekable();
682 /// // peek() lets us see into the future
683 /// assert_eq!(iter.peek(), Some(&&1));
684 /// assert_eq!(iter.next(), Some(&1));
686 /// assert_eq!(iter.next(), Some(&2));
688 /// // we can peek() multiple times, the iterator won't advance
689 /// assert_eq!(iter.peek(), Some(&&3));
690 /// assert_eq!(iter.peek(), Some(&&3));
692 /// assert_eq!(iter.next(), Some(&3));
694 /// // after the iterator is finished, so is peek()
695 /// assert_eq!(iter.peek(), None);
696 /// assert_eq!(iter.next(), None);
699 #[stable(feature = "rust1", since = "1.0.0")]
700 fn peekable(self) -> Peekable
<Self> where Self: Sized
{
701 Peekable{iter: self, peeked: None}
704 /// Creates an iterator that [`skip`]s elements based on a predicate.
706 /// [`skip`]: #method.skip
708 /// `skip_while()` takes a closure as an argument. It will call this
709 /// closure on each element of the iterator, and ignore elements
710 /// until it returns `false`.
712 /// After `false` is returned, `skip_while()`'s job is over, and the
713 /// rest of the elements are yielded.
720 /// let a = [-1i32, 0, 1];
722 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
724 /// assert_eq!(iter.next(), Some(&0));
725 /// assert_eq!(iter.next(), Some(&1));
726 /// assert_eq!(iter.next(), None);
729 /// Because the closure passed to `skip_while()` takes a reference, and many
730 /// iterators iterate over references, this leads to a possibly confusing
731 /// situation, where the type of the closure is a double reference:
734 /// let a = [-1, 0, 1];
736 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
738 /// assert_eq!(iter.next(), Some(&0));
739 /// assert_eq!(iter.next(), Some(&1));
740 /// assert_eq!(iter.next(), None);
743 /// Stopping after an initial `false`:
746 /// let a = [-1, 0, 1, -2];
748 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
750 /// assert_eq!(iter.next(), Some(&0));
751 /// assert_eq!(iter.next(), Some(&1));
753 /// // while this would have been false, since we already got a false,
754 /// // skip_while() isn't used any more
755 /// assert_eq!(iter.next(), Some(&-2));
757 /// assert_eq!(iter.next(), None);
760 #[stable(feature = "rust1", since = "1.0.0")]
761 fn skip_while
<P
>(self, predicate
: P
) -> SkipWhile
<Self, P
> where
762 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
764 SkipWhile{iter: self, flag: false, predicate: predicate}
767 /// Creates an iterator that yields elements based on a predicate.
769 /// `take_while()` takes a closure as an argument. It will call this
770 /// closure on each element of the iterator, and yield elements
771 /// while it returns `true`.
773 /// After `false` is returned, `take_while()`'s job is over, and the
774 /// rest of the elements are ignored.
781 /// let a = [-1i32, 0, 1];
783 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
785 /// assert_eq!(iter.next(), Some(&-1));
786 /// assert_eq!(iter.next(), None);
789 /// Because the closure passed to `take_while()` takes a reference, and many
790 /// iterators iterate over references, this leads to a possibly confusing
791 /// situation, where the type of the closure is a double reference:
794 /// let a = [-1, 0, 1];
796 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
798 /// assert_eq!(iter.next(), Some(&-1));
799 /// assert_eq!(iter.next(), None);
802 /// Stopping after an initial `false`:
805 /// let a = [-1, 0, 1, -2];
807 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
809 /// assert_eq!(iter.next(), Some(&-1));
811 /// // We have more elements that are less than zero, but since we already
812 /// // got a false, take_while() isn't used any more
813 /// assert_eq!(iter.next(), None);
816 /// Because `take_while()` needs to look at the value in order to see if it
817 /// should be included or not, consuming iterators will see that it is
821 /// let a = [1, 2, 3, 4];
822 /// let mut iter = a.into_iter();
824 /// let result: Vec<i32> = iter.by_ref()
825 /// .take_while(|n| **n != 3)
829 /// assert_eq!(result, &[1, 2]);
831 /// let result: Vec<i32> = iter.cloned().collect();
833 /// assert_eq!(result, &[4]);
836 /// The `3` is no longer there, because it was consumed in order to see if
837 /// the iteration should stop, but wasn't placed back into the iterator or
838 /// some similar thing.
840 #[stable(feature = "rust1", since = "1.0.0")]
841 fn take_while
<P
>(self, predicate
: P
) -> TakeWhile
<Self, P
> where
842 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
844 TakeWhile{iter: self, flag: false, predicate: predicate}
847 /// Creates an iterator that skips the first `n` elements.
849 /// After they have been consumed, the rest of the elements are yielded.
856 /// let a = [1, 2, 3];
858 /// let mut iter = a.iter().skip(2);
860 /// assert_eq!(iter.next(), Some(&3));
861 /// assert_eq!(iter.next(), None);
864 #[stable(feature = "rust1", since = "1.0.0")]
865 fn skip(self, n
: usize) -> Skip
<Self> where Self: Sized
{
866 Skip{iter: self, n: n}
869 /// Creates an iterator that yields its first `n` elements.
876 /// let a = [1, 2, 3];
878 /// let mut iter = a.iter().take(2);
880 /// assert_eq!(iter.next(), Some(&1));
881 /// assert_eq!(iter.next(), Some(&2));
882 /// assert_eq!(iter.next(), None);
885 /// `take()` is often used with an infinite iterator, to make it finite:
888 /// let mut iter = (0..).take(3);
890 /// assert_eq!(iter.next(), Some(0));
891 /// assert_eq!(iter.next(), Some(1));
892 /// assert_eq!(iter.next(), Some(2));
893 /// assert_eq!(iter.next(), None);
896 #[stable(feature = "rust1", since = "1.0.0")]
897 fn take(self, n
: usize) -> Take
<Self> where Self: Sized
, {
898 Take{iter: self, n: n}
901 /// An iterator adaptor similar to [`fold`] that holds internal state and
902 /// produces a new iterator.
904 /// [`fold`]: #method.fold
906 /// `scan()` takes two arguments: an initial value which seeds the internal
907 /// state, and a closure with two arguments, the first being a mutable
908 /// reference to the internal state and the second an iterator element.
909 /// The closure can assign to the internal state to share state between
912 /// On iteration, the closure will be applied to each element of the
913 /// iterator and the return value from the closure, an [`Option`], is
914 /// yielded by the iterator.
916 /// [`Option`]: ../../std/option/enum.Option.html
923 /// let a = [1, 2, 3];
925 /// let mut iter = a.iter().scan(1, |state, &x| {
926 /// // each iteration, we'll multiply the state by the element
927 /// *state = *state * x;
929 /// // the value passed on to the next iteration
933 /// assert_eq!(iter.next(), Some(1));
934 /// assert_eq!(iter.next(), Some(2));
935 /// assert_eq!(iter.next(), Some(6));
936 /// assert_eq!(iter.next(), None);
939 #[stable(feature = "rust1", since = "1.0.0")]
940 fn scan
<St
, B
, F
>(self, initial_state
: St
, f
: F
) -> Scan
<Self, St
, F
>
941 where Self: Sized
, F
: FnMut(&mut St
, Self::Item
) -> Option
<B
>,
943 Scan{iter: self, f: f, state: initial_state}
946 /// Creates an iterator that works like map, but flattens nested structure.
948 /// The [`map`] adapter is very useful, but only when the closure
949 /// argument produces values. If it produces an iterator instead, there's
950 /// an extra layer of indirection. `flat_map()` will remove this extra layer
953 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
954 /// one item for each element, and `flat_map()`'s closure returns an
955 /// iterator for each element.
957 /// [`map`]: #method.map
964 /// let words = ["alpha", "beta", "gamma"];
966 /// // chars() returns an iterator
967 /// let merged: String = words.iter()
968 /// .flat_map(|s| s.chars())
970 /// assert_eq!(merged, "alphabetagamma");
973 #[stable(feature = "rust1", since = "1.0.0")]
974 fn flat_map
<U
, F
>(self, f
: F
) -> FlatMap
<Self, U
, F
>
975 where Self: Sized
, U
: IntoIterator
, F
: FnMut(Self::Item
) -> U
,
977 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
980 /// Creates an iterator which ends after the first [`None`].
982 /// After an iterator returns [`None`], future calls may or may not yield
983 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
984 /// [`None`] is given, it will always return [`None`] forever.
986 /// [`None`]: ../../std/option/enum.Option.html#variant.None
987 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
994 /// // an iterator which alternates between Some and None
995 /// struct Alternate {
999 /// impl Iterator for Alternate {
1000 /// type Item = i32;
1002 /// fn next(&mut self) -> Option<i32> {
1003 /// let val = self.state;
1004 /// self.state = self.state + 1;
1006 /// // if it's even, Some(i32), else None
1007 /// if val % 2 == 0 {
1015 /// let mut iter = Alternate { state: 0 };
1017 /// // we can see our iterator going back and forth
1018 /// assert_eq!(iter.next(), Some(0));
1019 /// assert_eq!(iter.next(), None);
1020 /// assert_eq!(iter.next(), Some(2));
1021 /// assert_eq!(iter.next(), None);
1023 /// // however, once we fuse it...
1024 /// let mut iter = iter.fuse();
1026 /// assert_eq!(iter.next(), Some(4));
1027 /// assert_eq!(iter.next(), None);
1029 /// // it will always return None after the first time.
1030 /// assert_eq!(iter.next(), None);
1031 /// assert_eq!(iter.next(), None);
1032 /// assert_eq!(iter.next(), None);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 fn fuse(self) -> Fuse
<Self> where Self: Sized
{
1037 Fuse{iter: self, done: false}
1040 /// Do something with each element of an iterator, passing the value on.
1042 /// When using iterators, you'll often chain several of them together.
1043 /// While working on such code, you might want to check out what's
1044 /// happening at various parts in the pipeline. To do that, insert
1045 /// a call to `inspect()`.
1047 /// It's much more common for `inspect()` to be used as a debugging tool
1048 /// than to exist in your final code, but never say never.
1055 /// let a = [1, 4, 2, 3];
1057 /// // this iterator sequence is complex.
1058 /// let sum = a.iter()
1060 /// .filter(|&x| x % 2 == 0)
1061 /// .fold(0, |sum, i| sum + i);
1063 /// println!("{}", sum);
1065 /// // let's add some inspect() calls to investigate what's happening
1066 /// let sum = a.iter()
1068 /// .inspect(|x| println!("about to filter: {}", x))
1069 /// .filter(|&x| x % 2 == 0)
1070 /// .inspect(|x| println!("made it through filter: {}", x))
1071 /// .fold(0, |sum, i| sum + i);
1073 /// println!("{}", sum);
1076 /// This will print:
1079 /// about to filter: 1
1080 /// about to filter: 4
1081 /// made it through filter: 4
1082 /// about to filter: 2
1083 /// made it through filter: 2
1084 /// about to filter: 3
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 fn inspect
<F
>(self, f
: F
) -> Inspect
<Self, F
> where
1090 Self: Sized
, F
: FnMut(&Self::Item
),
1092 Inspect{iter: self, f: f}
1095 /// Borrows an iterator, rather than consuming it.
1097 /// This is useful to allow applying iterator adaptors while still
1098 /// retaining ownership of the original iterator.
1105 /// let a = [1, 2, 3];
1107 /// let iter = a.into_iter();
1109 /// let sum: i32 = iter.take(5)
1110 /// .fold(0, |acc, &i| acc + i );
1112 /// assert_eq!(sum, 6);
1114 /// // if we try to use iter again, it won't work. The following line
1115 /// // gives "error: use of moved value: `iter`
1116 /// // assert_eq!(iter.next(), None);
1118 /// // let's try that again
1119 /// let a = [1, 2, 3];
1121 /// let mut iter = a.into_iter();
1123 /// // instead, we add in a .by_ref()
1124 /// let sum: i32 = iter.by_ref()
1126 /// .fold(0, |acc, &i| acc + i );
1128 /// assert_eq!(sum, 3);
1130 /// // now this is just fine:
1131 /// assert_eq!(iter.next(), Some(&3));
1132 /// assert_eq!(iter.next(), None);
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1137 /// Transforms an iterator into a collection.
1139 /// `collect()` can take anything iterable, and turn it into a relevant
1140 /// collection. This is one of the more powerful methods in the standard
1141 /// library, used in a variety of contexts.
1143 /// The most basic pattern in which `collect()` is used is to turn one
1144 /// collection into another. You take a collection, call [`iter`] on it,
1145 /// do a bunch of transformations, and then `collect()` at the end.
1147 /// One of the keys to `collect()`'s power is that many things you might
1148 /// not think of as 'collections' actually are. For example, a [`String`]
1149 /// is a collection of [`char`]s. And a collection of
1150 /// [`Result<T, E>`][`Result`] can be thought of as single
1151 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1153 /// Because `collect()` is so general, it can cause problems with type
1154 /// inference. As such, `collect()` is one of the few times you'll see
1155 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1156 /// helps the inference algorithm understand specifically which collection
1157 /// you're trying to collect into.
1164 /// let a = [1, 2, 3];
1166 /// let doubled: Vec<i32> = a.iter()
1167 /// .map(|&x| x * 2)
1170 /// assert_eq!(vec![2, 4, 6], doubled);
1173 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1174 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1176 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1179 /// use std::collections::VecDeque;
1181 /// let a = [1, 2, 3];
1183 /// let doubled: VecDeque<i32> = a.iter()
1184 /// .map(|&x| x * 2)
1187 /// assert_eq!(2, doubled[0]);
1188 /// assert_eq!(4, doubled[1]);
1189 /// assert_eq!(6, doubled[2]);
1192 /// Using the 'turbofish' instead of annotating `doubled`:
1195 /// let a = [1, 2, 3];
1197 /// let doubled = a.iter()
1198 /// .map(|&x| x * 2)
1199 /// .collect::<Vec<i32>>();
1201 /// assert_eq!(vec![2, 4, 6], doubled);
1204 /// Because `collect()` cares about what you're collecting into, you can
1205 /// still use a partial type hint, `_`, with the turbofish:
1208 /// let a = [1, 2, 3];
1210 /// let doubled = a.iter()
1211 /// .map(|&x| x * 2)
1212 /// .collect::<Vec<_>>();
1214 /// assert_eq!(vec![2, 4, 6], doubled);
1217 /// Using `collect()` to make a [`String`]:
1220 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1222 /// let hello: String = chars.iter()
1223 /// .map(|&x| x as u8)
1224 /// .map(|x| (x + 1) as char)
1227 /// assert_eq!("hello", hello);
1230 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1231 /// see if any of them failed:
1234 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1236 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1238 /// // gives us the first error
1239 /// assert_eq!(Err("nope"), result);
1241 /// let results = [Ok(1), Ok(3)];
1243 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1245 /// // gives us the list of answers
1246 /// assert_eq!(Ok(vec![1, 3]), result);
1249 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1250 /// [`String`]: ../../std/string/struct.String.html
1251 /// [`char`]: ../../std/primitive.char.html
1252 /// [`Result`]: ../../std/result/enum.Result.html
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 fn collect
<B
: FromIterator
<Self::Item
>>(self) -> B
where Self: Sized
{
1256 FromIterator
::from_iter(self)
1259 /// Consumes an iterator, creating two collections from it.
1261 /// The predicate passed to `partition()` can return `true`, or `false`.
1262 /// `partition()` returns a pair, all of the elements for which it returned
1263 /// `true`, and all of the elements for which it returned `false`.
1270 /// let a = [1, 2, 3];
1272 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1273 /// .partition(|&n| n % 2 == 0);
1275 /// assert_eq!(even, vec![2]);
1276 /// assert_eq!(odd, vec![1, 3]);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 fn partition
<B
, F
>(self, mut f
: F
) -> (B
, B
) where
1281 B
: Default
+ Extend
<Self::Item
>,
1282 F
: FnMut(&Self::Item
) -> bool
1284 let mut left
: B
= Default
::default();
1285 let mut right
: B
= Default
::default();
1289 left
.extend(Some(x
))
1291 right
.extend(Some(x
))
1298 /// An iterator adaptor that applies a function, producing a single, final value.
1300 /// `fold()` takes two arguments: an initial value, and a closure with two
1301 /// arguments: an 'accumulator', and an element. The closure returns the value that
1302 /// the accumulator should have for the next iteration.
1304 /// The initial value is the value the accumulator will have on the first
1307 /// After applying this closure to every element of the iterator, `fold()`
1308 /// returns the accumulator.
1310 /// This operation is sometimes called 'reduce' or 'inject'.
1312 /// Folding is useful whenever you have a collection of something, and want
1313 /// to produce a single value from it.
1320 /// let a = [1, 2, 3];
1322 /// // the sum of all of the elements of a
1323 /// let sum = a.iter()
1324 /// .fold(0, |acc, &x| acc + x);
1326 /// assert_eq!(sum, 6);
1329 /// Let's walk through each step of the iteration here:
1331 /// | element | acc | x | result |
1332 /// |---------|-----|---|--------|
1334 /// | 1 | 0 | 1 | 1 |
1335 /// | 2 | 1 | 2 | 3 |
1336 /// | 3 | 3 | 3 | 6 |
1338 /// And so, our final result, `6`.
1340 /// It's common for people who haven't used iterators a lot to
1341 /// use a `for` loop with a list of things to build up a result. Those
1342 /// can be turned into `fold()`s:
1344 /// [`for`]: ../../book/first-edition/loops.html#for
1347 /// let numbers = [1, 2, 3, 4, 5];
1349 /// let mut result = 0;
1352 /// for i in &numbers {
1353 /// result = result + i;
1357 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1359 /// // they're the same
1360 /// assert_eq!(result, result2);
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 fn fold
<B
, F
>(self, init
: B
, mut f
: F
) -> B
where
1365 Self: Sized
, F
: FnMut(B
, Self::Item
) -> B
,
1367 let mut accum
= init
;
1369 accum
= f(accum
, x
);
1374 /// Tests if every element of the iterator matches a predicate.
1376 /// `all()` takes a closure that returns `true` or `false`. It applies
1377 /// this closure to each element of the iterator, and if they all return
1378 /// `true`, then so does `all()`. If any of them return `false`, it
1379 /// returns `false`.
1381 /// `all()` is short-circuiting; in other words, it will stop processing
1382 /// as soon as it finds a `false`, given that no matter what else happens,
1383 /// the result will also be `false`.
1385 /// An empty iterator returns `true`.
1392 /// let a = [1, 2, 3];
1394 /// assert!(a.iter().all(|&x| x > 0));
1396 /// assert!(!a.iter().all(|&x| x > 2));
1399 /// Stopping at the first `false`:
1402 /// let a = [1, 2, 3];
1404 /// let mut iter = a.iter();
1406 /// assert!(!iter.all(|&x| x != 2));
1408 /// // we can still use `iter`, as there are more elements.
1409 /// assert_eq!(iter.next(), Some(&3));
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 fn all
<F
>(&mut self, mut f
: F
) -> bool
where
1414 Self: Sized
, F
: FnMut(Self::Item
) -> bool
1424 /// Tests if any element of the iterator matches a predicate.
1426 /// `any()` takes a closure that returns `true` or `false`. It applies
1427 /// this closure to each element of the iterator, and if any of them return
1428 /// `true`, then so does `any()`. If they all return `false`, it
1429 /// returns `false`.
1431 /// `any()` is short-circuiting; in other words, it will stop processing
1432 /// as soon as it finds a `true`, given that no matter what else happens,
1433 /// the result will also be `true`.
1435 /// An empty iterator returns `false`.
1442 /// let a = [1, 2, 3];
1444 /// assert!(a.iter().any(|&x| x > 0));
1446 /// assert!(!a.iter().any(|&x| x > 5));
1449 /// Stopping at the first `true`:
1452 /// let a = [1, 2, 3];
1454 /// let mut iter = a.iter();
1456 /// assert!(iter.any(|&x| x != 2));
1458 /// // we can still use `iter`, as there are more elements.
1459 /// assert_eq!(iter.next(), Some(&2));
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 fn any
<F
>(&mut self, mut f
: F
) -> bool
where
1465 F
: FnMut(Self::Item
) -> bool
1475 /// Searches for an element of an iterator that satisfies a predicate.
1477 /// `find()` takes a closure that returns `true` or `false`. It applies
1478 /// this closure to each element of the iterator, and if any of them return
1479 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1480 /// `false`, it returns [`None`].
1482 /// `find()` is short-circuiting; in other words, it will stop processing
1483 /// as soon as the closure returns `true`.
1485 /// Because `find()` takes a reference, and many iterators iterate over
1486 /// references, this leads to a possibly confusing situation where the
1487 /// argument is a double reference. You can see this effect in the
1488 /// examples below, with `&&x`.
1490 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1491 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1498 /// let a = [1, 2, 3];
1500 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1502 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1505 /// Stopping at the first `true`:
1508 /// let a = [1, 2, 3];
1510 /// let mut iter = a.iter();
1512 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1514 /// // we can still use `iter`, as there are more elements.
1515 /// assert_eq!(iter.next(), Some(&3));
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 fn find
<P
>(&mut self, mut predicate
: P
) -> Option
<Self::Item
> where
1521 P
: FnMut(&Self::Item
) -> bool
,
1524 if predicate(&x
) { return Some(x) }
1529 /// Searches for an element in an iterator, returning its index.
1531 /// `position()` takes a closure that returns `true` or `false`. It applies
1532 /// this closure to each element of the iterator, and if one of them
1533 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1534 /// them return `false`, it returns [`None`].
1536 /// `position()` is short-circuiting; in other words, it will stop
1537 /// processing as soon as it finds a `true`.
1539 /// # Overflow Behavior
1541 /// The method does no guarding against overflows, so if there are more
1542 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1543 /// result or panics. If debug assertions are enabled, a panic is
1548 /// This function might panic if the iterator has more than `usize::MAX`
1549 /// non-matching elements.
1551 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1552 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1553 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1560 /// let a = [1, 2, 3];
1562 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1564 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1567 /// Stopping at the first `true`:
1570 /// let a = [1, 2, 3, 4];
1572 /// let mut iter = a.iter();
1574 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1576 /// // we can still use `iter`, as there are more elements.
1577 /// assert_eq!(iter.next(), Some(&3));
1579 /// // The returned index depends on iterator state
1580 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 fn position
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1587 P
: FnMut(Self::Item
) -> bool
,
1589 // `enumerate` might overflow.
1590 for (i
, x
) in self.enumerate() {
1598 /// Searches for an element in an iterator from the right, returning its
1601 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1602 /// this closure to each element of the iterator, starting from the end,
1603 /// and if one of them returns `true`, then `rposition()` returns
1604 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1606 /// `rposition()` is short-circuiting; in other words, it will stop
1607 /// processing as soon as it finds a `true`.
1609 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1610 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1617 /// let a = [1, 2, 3];
1619 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1621 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1624 /// Stopping at the first `true`:
1627 /// let a = [1, 2, 3];
1629 /// let mut iter = a.iter();
1631 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1633 /// // we can still use `iter`, as there are more elements.
1634 /// assert_eq!(iter.next(), Some(&1));
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 fn rposition
<P
>(&mut self, mut predicate
: P
) -> Option
<usize> where
1639 P
: FnMut(Self::Item
) -> bool
,
1640 Self: Sized
+ ExactSizeIterator
+ DoubleEndedIterator
1642 let mut i
= self.len();
1644 while let Some(v
) = self.next_back() {
1645 // No need for an overflow check here, because `ExactSizeIterator`
1646 // implies that the number of elements fits into a `usize`.
1655 /// Returns the maximum element of an iterator.
1657 /// If several elements are equally maximum, the last element is
1658 /// returned. If the iterator is empty, [`None`] is returned.
1660 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1667 /// let a = [1, 2, 3];
1668 /// let b: Vec<u32> = Vec::new();
1670 /// assert_eq!(a.iter().max(), Some(&3));
1671 /// assert_eq!(b.iter().max(), None);
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 fn max(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1679 // switch to y even if it is only equal, to preserve
1681 |_
, x
, _
, y
| *x
<= *y
)
1685 /// Returns the minimum element of an iterator.
1687 /// If several elements are equally minimum, the first element is
1688 /// returned. If the iterator is empty, [`None`] is returned.
1690 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1697 /// let a = [1, 2, 3];
1698 /// let b: Vec<u32> = Vec::new();
1700 /// assert_eq!(a.iter().min(), Some(&1));
1701 /// assert_eq!(b.iter().min(), None);
1704 #[stable(feature = "rust1", since = "1.0.0")]
1705 fn min(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
1709 // only switch to y if it is strictly smaller, to
1710 // preserve stability.
1711 |_
, x
, _
, y
| *x
> *y
)
1715 /// Returns the element that gives the maximum value from the
1716 /// specified function.
1718 /// If several elements are equally maximum, the last element is
1719 /// returned. If the iterator is empty, [`None`] is returned.
1721 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1726 /// let a = [-3_i32, 0, 1, 5, -10];
1727 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1730 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1731 fn max_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1732 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1736 // switch to y even if it is only equal, to preserve
1738 |x_p
, _
, y_p
, _
| x_p
<= y_p
)
1742 /// Returns the element that gives the maximum value with respect to the
1743 /// specified comparison function.
1745 /// If several elements are equally maximum, the last element is
1746 /// returned. If the iterator is empty, [`None`] is returned.
1748 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1753 /// let a = [-3_i32, 0, 1, 5, -10];
1754 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1757 #[stable(feature = "iter_max_by", since = "1.15.0")]
1758 fn max_by
<F
>(self, mut compare
: F
) -> Option
<Self::Item
>
1759 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
1763 // switch to y even if it is only equal, to preserve
1765 |_
, x
, _
, y
| Ordering
::Greater
!= compare(x
, y
))
1769 /// Returns the element that gives the minimum value from the
1770 /// specified function.
1772 /// If several elements are equally minimum, the first element is
1773 /// returned. If the iterator is empty, [`None`] is returned.
1775 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1780 /// let a = [-3_i32, 0, 1, 5, -10];
1781 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1783 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1784 fn min_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
1785 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
1789 // only switch to y if it is strictly smaller, to
1790 // preserve stability.
1791 |x_p
, _
, y_p
, _
| x_p
> y_p
)
1795 /// Returns the element that gives the minimum value with respect to the
1796 /// specified comparison function.
1798 /// If several elements are equally minimum, the first element is
1799 /// returned. If the iterator is empty, [`None`] is returned.
1801 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1806 /// let a = [-3_i32, 0, 1, 5, -10];
1807 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1810 #[stable(feature = "iter_min_by", since = "1.15.0")]
1811 fn min_by
<F
>(self, mut compare
: F
) -> Option
<Self::Item
>
1812 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
1816 // switch to y even if it is strictly smaller, to
1817 // preserve stability.
1818 |_
, x
, _
, y
| Ordering
::Greater
== compare(x
, y
))
1823 /// Reverses an iterator's direction.
1825 /// Usually, iterators iterate from left to right. After using `rev()`,
1826 /// an iterator will instead iterate from right to left.
1828 /// This is only possible if the iterator has an end, so `rev()` only
1829 /// works on [`DoubleEndedIterator`]s.
1831 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1836 /// let a = [1, 2, 3];
1838 /// let mut iter = a.iter().rev();
1840 /// assert_eq!(iter.next(), Some(&3));
1841 /// assert_eq!(iter.next(), Some(&2));
1842 /// assert_eq!(iter.next(), Some(&1));
1844 /// assert_eq!(iter.next(), None);
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 fn rev(self) -> Rev
<Self> where Self: Sized
+ DoubleEndedIterator
{
1852 /// Converts an iterator of pairs into a pair of containers.
1854 /// `unzip()` consumes an entire iterator of pairs, producing two
1855 /// collections: one from the left elements of the pairs, and one
1856 /// from the right elements.
1858 /// This function is, in some sense, the opposite of [`zip`].
1860 /// [`zip`]: #method.zip
1867 /// let a = [(1, 2), (3, 4)];
1869 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1871 /// assert_eq!(left, [1, 3]);
1872 /// assert_eq!(right, [2, 4]);
1874 #[stable(feature = "rust1", since = "1.0.0")]
1875 fn unzip
<A
, B
, FromA
, FromB
>(self) -> (FromA
, FromB
) where
1876 FromA
: Default
+ Extend
<A
>,
1877 FromB
: Default
+ Extend
<B
>,
1878 Self: Sized
+ Iterator
<Item
=(A
, B
)>,
1880 let mut ts
: FromA
= Default
::default();
1881 let mut us
: FromB
= Default
::default();
1883 for (t
, u
) in self {
1891 /// Creates an iterator which [`clone`]s all of its elements.
1893 /// This is useful when you have an iterator over `&T`, but you need an
1894 /// iterator over `T`.
1896 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
1903 /// let a = [1, 2, 3];
1905 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1907 /// // cloned is the same as .map(|&x| x), for integers
1908 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1910 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1911 /// assert_eq!(v_map, vec![1, 2, 3]);
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 fn cloned
<'a
, T
: 'a
>(self) -> Cloned
<Self>
1915 where Self: Sized
+ Iterator
<Item
=&'a T
>, T
: Clone
1920 /// Repeats an iterator endlessly.
1922 /// Instead of stopping at [`None`], the iterator will instead start again,
1923 /// from the beginning. After iterating again, it will start at the
1924 /// beginning again. And again. And again. Forever.
1926 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1933 /// let a = [1, 2, 3];
1935 /// let mut it = a.iter().cycle();
1937 /// assert_eq!(it.next(), Some(&1));
1938 /// assert_eq!(it.next(), Some(&2));
1939 /// assert_eq!(it.next(), Some(&3));
1940 /// assert_eq!(it.next(), Some(&1));
1941 /// assert_eq!(it.next(), Some(&2));
1942 /// assert_eq!(it.next(), Some(&3));
1943 /// assert_eq!(it.next(), Some(&1));
1945 #[stable(feature = "rust1", since = "1.0.0")]
1947 fn cycle(self) -> Cycle
<Self> where Self: Sized
+ Clone
{
1948 Cycle{orig: self.clone(), iter: self}
1951 /// Sums the elements of an iterator.
1953 /// Takes each element, adds them together, and returns the result.
1955 /// An empty iterator returns the zero value of the type.
1959 /// When calling `sum()` and a primitive integer type is being returned, this
1960 /// method will panic if the computation overflows and debug assertions are
1968 /// let a = [1, 2, 3];
1969 /// let sum: i32 = a.iter().sum();
1971 /// assert_eq!(sum, 6);
1973 #[stable(feature = "iter_arith", since = "1.11.0")]
1974 fn sum
<S
>(self) -> S
1981 /// Iterates over the entire iterator, multiplying all the elements
1983 /// An empty iterator returns the one value of the type.
1987 /// When calling `product()` and a primitive integer type is being returned,
1988 /// method will panic if the computation overflows and debug assertions are
1994 /// fn factorial(n: u32) -> u32 {
1995 /// (1..).take_while(|&i| i <= n).product()
1997 /// assert_eq!(factorial(0), 1);
1998 /// assert_eq!(factorial(1), 1);
1999 /// assert_eq!(factorial(5), 120);
2001 #[stable(feature = "iter_arith", since = "1.11.0")]
2002 fn product
<P
>(self) -> P
2004 P
: Product
<Self::Item
>,
2006 Product
::product(self)
2009 /// Lexicographically compares the elements of this `Iterator` with those
2011 #[stable(feature = "iter_order", since = "1.5.0")]
2012 fn cmp
<I
>(mut self, other
: I
) -> Ordering
where
2013 I
: IntoIterator
<Item
= Self::Item
>,
2017 let mut other
= other
.into_iter();
2020 match (self.next(), other
.next()) {
2021 (None
, None
) => return Ordering
::Equal
,
2022 (None
, _
) => return Ordering
::Less
,
2023 (_
, None
) => return Ordering
::Greater
,
2024 (Some(x
), Some(y
)) => match x
.cmp(&y
) {
2025 Ordering
::Equal
=> (),
2026 non_eq
=> return non_eq
,
2032 /// Lexicographically compares the elements of this `Iterator` with those
2034 #[stable(feature = "iter_order", since = "1.5.0")]
2035 fn partial_cmp
<I
>(mut self, other
: I
) -> Option
<Ordering
> where
2037 Self::Item
: PartialOrd
<I
::Item
>,
2040 let mut other
= other
.into_iter();
2043 match (self.next(), other
.next()) {
2044 (None
, None
) => return Some(Ordering
::Equal
),
2045 (None
, _
) => return Some(Ordering
::Less
),
2046 (_
, None
) => return Some(Ordering
::Greater
),
2047 (Some(x
), Some(y
)) => match x
.partial_cmp(&y
) {
2048 Some(Ordering
::Equal
) => (),
2049 non_eq
=> return non_eq
,
2055 /// Determines if the elements of this `Iterator` are equal to those of
2057 #[stable(feature = "iter_order", since = "1.5.0")]
2058 fn eq
<I
>(mut self, other
: I
) -> bool
where
2060 Self::Item
: PartialEq
<I
::Item
>,
2063 let mut other
= other
.into_iter();
2066 match (self.next(), other
.next()) {
2067 (None
, None
) => return true,
2068 (None
, _
) | (_
, None
) => return false,
2069 (Some(x
), Some(y
)) => if x
!= y { return false }
,
2074 /// Determines if the elements of this `Iterator` are unequal to those of
2076 #[stable(feature = "iter_order", since = "1.5.0")]
2077 fn ne
<I
>(mut self, other
: I
) -> bool
where
2079 Self::Item
: PartialEq
<I
::Item
>,
2082 let mut other
= other
.into_iter();
2085 match (self.next(), other
.next()) {
2086 (None
, None
) => return false,
2087 (None
, _
) | (_
, None
) => return true,
2088 (Some(x
), Some(y
)) => if x
.ne(&y
) { return true }
,
2093 /// Determines if the elements of this `Iterator` are lexicographically
2094 /// less than those of another.
2095 #[stable(feature = "iter_order", since = "1.5.0")]
2096 fn lt
<I
>(mut self, other
: I
) -> bool
where
2098 Self::Item
: PartialOrd
<I
::Item
>,
2101 let mut other
= other
.into_iter();
2104 match (self.next(), other
.next()) {
2105 (None
, None
) => return false,
2106 (None
, _
) => return true,
2107 (_
, None
) => return false,
2108 (Some(x
), Some(y
)) => {
2109 match x
.partial_cmp(&y
) {
2110 Some(Ordering
::Less
) => return true,
2111 Some(Ordering
::Equal
) => {}
2112 Some(Ordering
::Greater
) => return false,
2113 None
=> return false,
2120 /// Determines if the elements of this `Iterator` are lexicographically
2121 /// less or equal to those of another.
2122 #[stable(feature = "iter_order", since = "1.5.0")]
2123 fn le
<I
>(mut self, other
: I
) -> bool
where
2125 Self::Item
: PartialOrd
<I
::Item
>,
2128 let mut other
= other
.into_iter();
2131 match (self.next(), other
.next()) {
2132 (None
, None
) => return true,
2133 (None
, _
) => return true,
2134 (_
, None
) => return false,
2135 (Some(x
), Some(y
)) => {
2136 match x
.partial_cmp(&y
) {
2137 Some(Ordering
::Less
) => return true,
2138 Some(Ordering
::Equal
) => {}
2139 Some(Ordering
::Greater
) => return false,
2140 None
=> return false,
2147 /// Determines if the elements of this `Iterator` are lexicographically
2148 /// greater than those of another.
2149 #[stable(feature = "iter_order", since = "1.5.0")]
2150 fn gt
<I
>(mut self, other
: I
) -> bool
where
2152 Self::Item
: PartialOrd
<I
::Item
>,
2155 let mut other
= other
.into_iter();
2158 match (self.next(), other
.next()) {
2159 (None
, None
) => return false,
2160 (None
, _
) => return false,
2161 (_
, None
) => return true,
2162 (Some(x
), Some(y
)) => {
2163 match x
.partial_cmp(&y
) {
2164 Some(Ordering
::Less
) => return false,
2165 Some(Ordering
::Equal
) => {}
2166 Some(Ordering
::Greater
) => return true,
2167 None
=> return false,
2174 /// Determines if the elements of this `Iterator` are lexicographically
2175 /// greater than or equal to those of another.
2176 #[stable(feature = "iter_order", since = "1.5.0")]
2177 fn ge
<I
>(mut self, other
: I
) -> bool
where
2179 Self::Item
: PartialOrd
<I
::Item
>,
2182 let mut other
= other
.into_iter();
2185 match (self.next(), other
.next()) {
2186 (None
, None
) => return true,
2187 (None
, _
) => return false,
2188 (_
, None
) => return true,
2189 (Some(x
), Some(y
)) => {
2190 match x
.partial_cmp(&y
) {
2191 Some(Ordering
::Less
) => return false,
2192 Some(Ordering
::Equal
) => {}
2193 Some(Ordering
::Greater
) => return true,
2194 None
=> return false,
2202 /// Select an element from an iterator based on the given "projection"
2203 /// and "comparison" function.
2205 /// This is an idiosyncratic helper to try to factor out the
2206 /// commonalities of {max,min}{,_by}. In particular, this avoids
2207 /// having to implement optimizations several times.
2209 fn select_fold1
<I
, B
, FProj
, FCmp
>(mut it
: I
,
2211 mut f_cmp
: FCmp
) -> Option
<(B
, I
::Item
)>
2213 FProj
: FnMut(&I
::Item
) -> B
,
2214 FCmp
: FnMut(&B
, &I
::Item
, &B
, &I
::Item
) -> bool
2216 // start with the first element as our selection. This avoids
2217 // having to use `Option`s inside the loop, translating to a
2218 // sizeable performance gain (6x in one case).
2219 it
.next().map(|mut sel
| {
2220 let mut sel_p
= f_proj(&sel
);
2223 let x_p
= f_proj(&x
);
2224 if f_cmp(&sel_p
, &sel
, &x_p
, &x
) {
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 impl<'a
, I
: Iterator
+ ?Sized
> Iterator
for &'a
mut I
{
2235 type Item
= I
::Item
;
2236 fn next(&mut self) -> Option
<I
::Item
> { (**self).next() }
2237 fn size_hint(&self) -> (usize, Option
<usize>) { (**self).size_hint() }
2238 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {