1 // ignore-tidy-filelength
2 // This file almost exclusively consists of the definition of `Iterator`. We
3 // can't split that into multiple files.
5 use crate::cmp::{self, Ordering};
6 use crate::ops::{Add, Try};
8 use super::super::LoopState;
9 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
10 use super::super::{FlatMap, Flatten};
11 use super::super::{FromIterator, Product, Sum, Zip};
13 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
16 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
18 /// An interface for dealing with iterators.
20 /// This is the main iterator trait. For more about the concept of iterators
21 /// generally, please see the [module-level documentation]. In particular, you
22 /// may want to know how to [implement `Iterator`][impl].
24 /// [module-level documentation]: index.html
25 /// [impl]: index.html#implementing-iterator
26 #[stable(feature = "rust1", since = "1.0.0")]
27 #[rustc_on_unimplemented(
29 _Self = "[std::ops::Range<Idx>; 1]",
30 label = "if you meant to iterate between two values, remove the square brackets",
31 note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
32 without the brackets: `start..end`"
35 _Self = "[std::ops::RangeFrom<Idx>; 1]",
36 label = "if you meant to iterate from a value onwards, remove the square brackets",
37 note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
38 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
39 unbounded iterator will run forever unless you `break` or `return` from within the \
43 _Self = "[std::ops::RangeTo<Idx>; 1]",
44 label = "if you meant to iterate until a value, remove the square brackets and add a \
46 note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
47 `Range` without the brackets: `0..end`"
50 _Self = "[std::ops::RangeInclusive<Idx>; 1]",
51 label = "if you meant to iterate between two values, remove the square brackets",
52 note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
53 `RangeInclusive` without the brackets: `start..=end`"
56 _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
57 label = "if you meant to iterate until a value (including it), remove the square brackets \
58 and add a starting value",
59 note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
60 bounded `RangeInclusive` without the brackets: `0..=end`"
63 _Self = "std::ops::RangeTo<Idx>",
64 label = "if you meant to iterate until a value, add a starting value",
65 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
66 bounded `Range`: `0..end`"
69 _Self = "std::ops::RangeToInclusive<Idx>",
70 label = "if you meant to iterate until a value (including it), add a starting value",
71 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
72 to have a bounded `RangeInclusive`: `0..=end`"
76 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
79 _Self = "std::string::String",
80 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 label = "borrow the array with `&` or call `.iter()` on it to iterate over it",
85 note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
89 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
90 syntax `start..end` or the inclusive range syntax `start..=end`"
92 label = "`{Self}` is not an iterator",
93 message = "`{Self}` is not an iterator"
95 #[must_use = "iterators are lazy and do nothing unless consumed"]
97 /// The type of the elements being iterated over.
98 #[stable(feature = "rust1", since = "1.0.0")]
101 /// Advances the iterator and returns the next value.
103 /// Returns [`None`] when iteration is finished. Individual iterator
104 /// implementations may choose to resume iteration, and so calling `next()`
105 /// again may or may not eventually start returning [`Some(Item)`] again at some
108 /// [`None`]: ../../std/option/enum.Option.html#variant.None
109 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
116 /// let a = [1, 2, 3];
118 /// let mut iter = a.iter();
120 /// // A call to next() returns the next value...
121 /// assert_eq!(Some(&1), iter.next());
122 /// assert_eq!(Some(&2), iter.next());
123 /// assert_eq!(Some(&3), iter.next());
125 /// // ... and then None once it's over.
126 /// assert_eq!(None, iter.next());
128 /// // More calls may or may not return `None`. Here, they always will.
129 /// assert_eq!(None, iter.next());
130 /// assert_eq!(None, iter.next());
132 #[stable(feature = "rust1", since = "1.0.0")]
133 fn next(&mut self) -> Option<Self::Item>;
135 /// Returns the bounds on the remaining length of the iterator.
137 /// Specifically, `size_hint()` returns a tuple where the first element
138 /// is the lower bound, and the second element is the upper bound.
140 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
141 /// A [`None`] here means that either there is no known upper bound, or the
142 /// upper bound is larger than [`usize`].
144 /// # Implementation notes
146 /// It is not enforced that an iterator implementation yields the declared
147 /// number of elements. A buggy iterator may yield less than the lower bound
148 /// or more than the upper bound of elements.
150 /// `size_hint()` is primarily intended to be used for optimizations such as
151 /// reserving space for the elements of the iterator, but must not be
152 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
153 /// implementation of `size_hint()` should not lead to memory safety
156 /// That said, the implementation should provide a correct estimation,
157 /// because otherwise it would be a violation of the trait's protocol.
159 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
162 /// [`usize`]: ../../std/primitive.usize.html
163 /// [`Option`]: ../../std/option/enum.Option.html
164 /// [`None`]: ../../std/option/enum.Option.html#variant.None
171 /// let a = [1, 2, 3];
172 /// let iter = a.iter();
174 /// assert_eq!((3, Some(3)), iter.size_hint());
177 /// A more complex example:
180 /// // The even numbers from zero to ten.
181 /// let iter = (0..10).filter(|x| x % 2 == 0);
183 /// // We might iterate from zero to ten times. Knowing that it's five
184 /// // exactly wouldn't be possible without executing filter().
185 /// assert_eq!((0, Some(10)), iter.size_hint());
187 /// // Let's add five more numbers with chain()
188 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
190 /// // now both bounds are increased by five
191 /// assert_eq!((5, Some(15)), iter.size_hint());
194 /// Returning `None` for an upper bound:
197 /// // an infinite iterator has no upper bound
198 /// // and the maximum possible lower bound
201 /// assert_eq!((usize::MAX, None), iter.size_hint());
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn size_hint(&self) -> (usize, Option<usize>) {
209 /// Consumes the iterator, counting the number of iterations and returning it.
211 /// This method will call [`next`] repeatedly until [`None`] is encountered,
212 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213 /// called at least once even if the iterator does not have any elements.
215 /// [`next`]: #tymethod.next
216 /// [`None`]: ../../std/option/enum.Option.html#variant.None
217 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
219 /// # Overflow Behavior
221 /// The method does no guarding against overflows, so counting elements of
222 /// an iterator with more than [`usize::MAX`] elements either produces the
223 /// wrong result or panics. If debug assertions are enabled, a panic is
228 /// This function might panic if the iterator has more than [`usize::MAX`]
231 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
238 /// let a = [1, 2, 3];
239 /// assert_eq!(a.iter().count(), 3);
241 /// let a = [1, 2, 3, 4, 5];
242 /// assert_eq!(a.iter().count(), 5);
245 #[stable(feature = "rust1", since = "1.0.0")]
246 fn count(self) -> usize
251 fn add1<T>(count: usize, _: T) -> usize {
259 /// Consumes the iterator, returning the last element.
261 /// This method will evaluate the iterator until it returns [`None`]. While
262 /// doing so, it keeps track of the current element. After [`None`] is
263 /// returned, `last()` will then return the last element it saw.
265 /// [`None`]: ../../std/option/enum.Option.html#variant.None
272 /// let a = [1, 2, 3];
273 /// assert_eq!(a.iter().last(), Some(&3));
275 /// let a = [1, 2, 3, 4, 5];
276 /// assert_eq!(a.iter().last(), Some(&5));
279 #[stable(feature = "rust1", since = "1.0.0")]
280 fn last(self) -> Option<Self::Item>
285 fn some<T>(_: Option<T>, x: T) -> Option<T> {
289 self.fold(None, some)
292 /// Returns the `n`th element of the iterator.
294 /// Like most indexing operations, the count starts from zero, so `nth(0)`
295 /// returns the first value, `nth(1)` the second, and so on.
297 /// Note that all preceding elements, as well as the returned element, will be
298 /// consumed from the iterator. That means that the preceding elements will be
299 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
300 /// will return different elements.
302 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
305 /// [`None`]: ../../std/option/enum.Option.html#variant.None
312 /// let a = [1, 2, 3];
313 /// assert_eq!(a.iter().nth(1), Some(&2));
316 /// Calling `nth()` multiple times doesn't rewind the iterator:
319 /// let a = [1, 2, 3];
321 /// let mut iter = a.iter();
323 /// assert_eq!(iter.nth(1), Some(&2));
324 /// assert_eq!(iter.nth(1), None);
327 /// Returning `None` if there are less than `n + 1` elements:
330 /// let a = [1, 2, 3];
331 /// assert_eq!(a.iter().nth(10), None);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
336 while let Some(x) = self.next() {
345 /// Creates an iterator starting at the same point, but stepping by
346 /// the given amount at each iteration.
348 /// Note 1: The first element of the iterator will always be returned,
349 /// regardless of the step given.
351 /// Note 2: The time at which ignored elements are pulled is not fixed.
352 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
353 /// but is also free to behave like the sequence
354 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
355 /// Which way is used may change for some iterators for performance reasons.
356 /// The second way will advance the iterator earlier and may consume more items.
358 /// `advance_n_and_return_first` is the equivalent of:
360 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
364 /// let next = iter.next();
365 /// if total_step > 1 {
366 /// iter.nth(total_step-2);
374 /// The method will panic if the given step is `0`.
381 /// let a = [0, 1, 2, 3, 4, 5];
382 /// let mut iter = a.iter().step_by(2);
384 /// assert_eq!(iter.next(), Some(&0));
385 /// assert_eq!(iter.next(), Some(&2));
386 /// assert_eq!(iter.next(), Some(&4));
387 /// assert_eq!(iter.next(), None);
390 #[stable(feature = "iterator_step_by", since = "1.28.0")]
391 fn step_by(self, step: usize) -> StepBy<Self>
395 StepBy::new(self, step)
398 /// Takes two iterators and creates a new iterator over both in sequence.
400 /// `chain()` will return a new iterator which will first iterate over
401 /// values from the first iterator and then over values from the second
404 /// In other words, it links two iterators together, in a chain. 🔗
406 /// [`once`] is commonly used to adapt a single value into a chain of
407 /// other kinds of iteration.
414 /// let a1 = [1, 2, 3];
415 /// let a2 = [4, 5, 6];
417 /// let mut iter = a1.iter().chain(a2.iter());
419 /// assert_eq!(iter.next(), Some(&1));
420 /// assert_eq!(iter.next(), Some(&2));
421 /// assert_eq!(iter.next(), Some(&3));
422 /// assert_eq!(iter.next(), Some(&4));
423 /// assert_eq!(iter.next(), Some(&5));
424 /// assert_eq!(iter.next(), Some(&6));
425 /// assert_eq!(iter.next(), None);
428 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
429 /// anything that can be converted into an [`Iterator`], not just an
430 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
431 /// [`IntoIterator`], and so can be passed to `chain()` directly:
434 /// let s1 = &[1, 2, 3];
435 /// let s2 = &[4, 5, 6];
437 /// let mut iter = s1.iter().chain(s2);
439 /// assert_eq!(iter.next(), Some(&1));
440 /// assert_eq!(iter.next(), Some(&2));
441 /// assert_eq!(iter.next(), Some(&3));
442 /// assert_eq!(iter.next(), Some(&4));
443 /// assert_eq!(iter.next(), Some(&5));
444 /// assert_eq!(iter.next(), Some(&6));
445 /// assert_eq!(iter.next(), None);
448 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
452 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
453 /// use std::os::windows::ffi::OsStrExt;
454 /// s.encode_wide().chain(std::iter::once(0)).collect()
458 /// [`once`]: fn.once.html
459 /// [`Iterator`]: trait.Iterator.html
460 /// [`IntoIterator`]: trait.IntoIterator.html
461 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
463 #[stable(feature = "rust1", since = "1.0.0")]
464 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
467 U: IntoIterator<Item = Self::Item>,
469 Chain::new(self, other.into_iter())
472 /// 'Zips up' two iterators into a single iterator of pairs.
474 /// `zip()` returns a new iterator that will iterate over two other
475 /// iterators, returning a tuple where the first element comes from the
476 /// first iterator, and the second element comes from the second iterator.
478 /// In other words, it zips two iterators together, into a single one.
480 /// If either iterator returns [`None`], [`next`] from the zipped iterator
481 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
482 /// short-circuit and `next` will not be called on the second iterator.
489 /// let a1 = [1, 2, 3];
490 /// let a2 = [4, 5, 6];
492 /// let mut iter = a1.iter().zip(a2.iter());
494 /// assert_eq!(iter.next(), Some((&1, &4)));
495 /// assert_eq!(iter.next(), Some((&2, &5)));
496 /// assert_eq!(iter.next(), Some((&3, &6)));
497 /// assert_eq!(iter.next(), None);
500 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
501 /// anything that can be converted into an [`Iterator`], not just an
502 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
503 /// [`IntoIterator`], and so can be passed to `zip()` directly:
505 /// [`IntoIterator`]: trait.IntoIterator.html
506 /// [`Iterator`]: trait.Iterator.html
509 /// let s1 = &[1, 2, 3];
510 /// let s2 = &[4, 5, 6];
512 /// let mut iter = s1.iter().zip(s2);
514 /// assert_eq!(iter.next(), Some((&1, &4)));
515 /// assert_eq!(iter.next(), Some((&2, &5)));
516 /// assert_eq!(iter.next(), Some((&3, &6)));
517 /// assert_eq!(iter.next(), None);
520 /// `zip()` is often used to zip an infinite iterator to a finite one.
521 /// This works because the finite iterator will eventually return [`None`],
522 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
525 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
527 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
529 /// assert_eq!((0, 'f'), enumerate[0]);
530 /// assert_eq!((0, 'f'), zipper[0]);
532 /// assert_eq!((1, 'o'), enumerate[1]);
533 /// assert_eq!((1, 'o'), zipper[1]);
535 /// assert_eq!((2, 'o'), enumerate[2]);
536 /// assert_eq!((2, 'o'), zipper[2]);
539 /// [`enumerate`]: trait.Iterator.html#method.enumerate
540 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
541 /// [`None`]: ../../std/option/enum.Option.html#variant.None
543 #[stable(feature = "rust1", since = "1.0.0")]
544 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
549 Zip::new(self, other.into_iter())
552 /// Takes a closure and creates an iterator which calls that closure on each
555 /// `map()` transforms one iterator into another, by means of its argument:
556 /// something that implements [`FnMut`]. It produces a new iterator which
557 /// calls this closure on each element of the original iterator.
559 /// If you are good at thinking in types, you can think of `map()` like this:
560 /// If you have an iterator that gives you elements of some type `A`, and
561 /// you want an iterator of some other type `B`, you can use `map()`,
562 /// passing a closure that takes an `A` and returns a `B`.
564 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
565 /// lazy, it is best used when you're already working with other iterators.
566 /// If you're doing some sort of looping for a side effect, it's considered
567 /// more idiomatic to use [`for`] than `map()`.
569 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
570 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
577 /// let a = [1, 2, 3];
579 /// let mut iter = a.iter().map(|x| 2 * x);
581 /// assert_eq!(iter.next(), Some(2));
582 /// assert_eq!(iter.next(), Some(4));
583 /// assert_eq!(iter.next(), Some(6));
584 /// assert_eq!(iter.next(), None);
587 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
590 /// # #![allow(unused_must_use)]
591 /// // don't do this:
592 /// (0..5).map(|x| println!("{}", x));
594 /// // it won't even execute, as it is lazy. Rust will warn you about this.
596 /// // Instead, use for:
598 /// println!("{}", x);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 fn map<B, F>(self, f: F) -> Map<Self, F>
606 F: FnMut(Self::Item) -> B,
611 /// Calls a closure on each element of an iterator.
613 /// This is equivalent to using a [`for`] loop on the iterator, although
614 /// `break` and `continue` are not possible from a closure. It's generally
615 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
616 /// when processing items at the end of longer iterator chains. In some
617 /// cases `for_each` may also be faster than a loop, because it will use
618 /// internal iteration on adaptors like `Chain`.
620 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
627 /// use std::sync::mpsc::channel;
629 /// let (tx, rx) = channel();
630 /// (0..5).map(|x| x * 2 + 1)
631 /// .for_each(move |x| tx.send(x).unwrap());
633 /// let v: Vec<_> = rx.iter().collect();
634 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
637 /// For such a small example, a `for` loop may be cleaner, but `for_each`
638 /// might be preferable to keep a functional style with longer iterators:
641 /// (0..5).flat_map(|x| x * 100 .. x * 110)
643 /// .filter(|&(i, x)| (i + x) % 3 == 0)
644 /// .for_each(|(i, x)| println!("{}:{}", i, x));
647 #[stable(feature = "iterator_for_each", since = "1.21.0")]
648 fn for_each<F>(self, f: F)
651 F: FnMut(Self::Item),
654 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
655 move |(), item| f(item)
658 self.fold((), call(f));
661 /// Creates an iterator which uses a closure to determine if an element
662 /// should be yielded.
664 /// The closure must return `true` or `false`. `filter()` creates an
665 /// iterator which calls this closure on each element. If the closure
666 /// returns `true`, then the element is returned. If the closure returns
667 /// `false`, it will try again, and call the closure on the next element,
668 /// seeing if it passes the test.
675 /// let a = [0i32, 1, 2];
677 /// let mut iter = a.iter().filter(|x| x.is_positive());
679 /// assert_eq!(iter.next(), Some(&1));
680 /// assert_eq!(iter.next(), Some(&2));
681 /// assert_eq!(iter.next(), None);
684 /// Because the closure passed to `filter()` takes a reference, and many
685 /// iterators iterate over references, this leads to a possibly confusing
686 /// situation, where the type of the closure is a double reference:
689 /// let a = [0, 1, 2];
691 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
693 /// assert_eq!(iter.next(), Some(&2));
694 /// assert_eq!(iter.next(), None);
697 /// It's common to instead use destructuring on the argument to strip away
701 /// let a = [0, 1, 2];
703 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
705 /// assert_eq!(iter.next(), Some(&2));
706 /// assert_eq!(iter.next(), None);
712 /// let a = [0, 1, 2];
714 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
716 /// assert_eq!(iter.next(), Some(&2));
717 /// assert_eq!(iter.next(), None);
722 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn filter<P>(self, predicate: P) -> Filter<Self, P>
728 P: FnMut(&Self::Item) -> bool,
730 Filter::new(self, predicate)
733 /// Creates an iterator that both filters and maps.
735 /// The closure must return an [`Option<T>`]. `filter_map` creates an
736 /// iterator which calls this closure on each element. If the closure
737 /// returns [`Some(element)`][`Some`], then that element is returned. If the
738 /// closure returns [`None`], it will try again, and call the closure on the
739 /// next element, seeing if it will return [`Some`].
741 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
744 /// [`filter`]: #method.filter
745 /// [`map`]: #method.map
747 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
749 /// In other words, it removes the [`Option<T>`] layer automatically. If your
750 /// mapping is already returning an [`Option<T>`] and you want to skip over
751 /// [`None`]s, then `filter_map` is much, much nicer to use.
758 /// let a = ["1", "lol", "3", "NaN", "5"];
760 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
762 /// assert_eq!(iter.next(), Some(1));
763 /// assert_eq!(iter.next(), Some(3));
764 /// assert_eq!(iter.next(), Some(5));
765 /// assert_eq!(iter.next(), None);
768 /// Here's the same example, but with [`filter`] and [`map`]:
771 /// let a = ["1", "lol", "3", "NaN", "5"];
772 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
773 /// assert_eq!(iter.next(), Some(1));
774 /// assert_eq!(iter.next(), Some(3));
775 /// assert_eq!(iter.next(), Some(5));
776 /// assert_eq!(iter.next(), None);
779 /// [`Option<T>`]: ../../std/option/enum.Option.html
780 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
781 /// [`None`]: ../../std/option/enum.Option.html#variant.None
783 #[stable(feature = "rust1", since = "1.0.0")]
784 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
787 F: FnMut(Self::Item) -> Option<B>,
789 FilterMap::new(self, f)
792 /// Creates an iterator which gives the current iteration count as well as
795 /// The iterator returned yields pairs `(i, val)`, where `i` is the
796 /// current index of iteration and `val` is the value returned by the
799 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
800 /// different sized integer, the [`zip`] function provides similar
803 /// # Overflow Behavior
805 /// The method does no guarding against overflows, so enumerating more than
806 /// [`usize::MAX`] elements either produces the wrong result or panics. If
807 /// debug assertions are enabled, a panic is guaranteed.
811 /// The returned iterator might panic if the to-be-returned index would
812 /// overflow a [`usize`].
814 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
815 /// [`usize`]: ../../std/primitive.usize.html
816 /// [`zip`]: #method.zip
821 /// let a = ['a', 'b', 'c'];
823 /// let mut iter = a.iter().enumerate();
825 /// assert_eq!(iter.next(), Some((0, &'a')));
826 /// assert_eq!(iter.next(), Some((1, &'b')));
827 /// assert_eq!(iter.next(), Some((2, &'c')));
828 /// assert_eq!(iter.next(), None);
831 #[stable(feature = "rust1", since = "1.0.0")]
832 fn enumerate(self) -> Enumerate<Self>
839 /// Creates an iterator which can use `peek` to look at the next element of
840 /// the iterator without consuming it.
842 /// Adds a [`peek`] method to an iterator. See its documentation for
843 /// more information.
845 /// Note that the underlying iterator is still advanced when [`peek`] is
846 /// called for the first time: In order to retrieve the next element,
847 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
848 /// anything other than fetching the next value) of the [`next`] method
851 /// [`peek`]: struct.Peekable.html#method.peek
852 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
859 /// let xs = [1, 2, 3];
861 /// let mut iter = xs.iter().peekable();
863 /// // peek() lets us see into the future
864 /// assert_eq!(iter.peek(), Some(&&1));
865 /// assert_eq!(iter.next(), Some(&1));
867 /// assert_eq!(iter.next(), Some(&2));
869 /// // we can peek() multiple times, the iterator won't advance
870 /// assert_eq!(iter.peek(), Some(&&3));
871 /// assert_eq!(iter.peek(), Some(&&3));
873 /// assert_eq!(iter.next(), Some(&3));
875 /// // after the iterator is finished, so is peek()
876 /// assert_eq!(iter.peek(), None);
877 /// assert_eq!(iter.next(), None);
880 #[stable(feature = "rust1", since = "1.0.0")]
881 fn peekable(self) -> Peekable<Self>
888 /// Creates an iterator that [`skip`]s elements based on a predicate.
890 /// [`skip`]: #method.skip
892 /// `skip_while()` takes a closure as an argument. It will call this
893 /// closure on each element of the iterator, and ignore elements
894 /// until it returns `false`.
896 /// After `false` is returned, `skip_while()`'s job is over, and the
897 /// rest of the elements are yielded.
904 /// let a = [-1i32, 0, 1];
906 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
908 /// assert_eq!(iter.next(), Some(&0));
909 /// assert_eq!(iter.next(), Some(&1));
910 /// assert_eq!(iter.next(), None);
913 /// Because the closure passed to `skip_while()` takes a reference, and many
914 /// iterators iterate over references, this leads to a possibly confusing
915 /// situation, where the type of the closure is a double reference:
918 /// let a = [-1, 0, 1];
920 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
922 /// assert_eq!(iter.next(), Some(&0));
923 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), None);
927 /// Stopping after an initial `false`:
930 /// let a = [-1, 0, 1, -2];
932 /// let mut iter = a.iter().skip_while(|x| **x < 0);
934 /// assert_eq!(iter.next(), Some(&0));
935 /// assert_eq!(iter.next(), Some(&1));
937 /// // while this would have been false, since we already got a false,
938 /// // skip_while() isn't used any more
939 /// assert_eq!(iter.next(), Some(&-2));
941 /// assert_eq!(iter.next(), None);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
948 P: FnMut(&Self::Item) -> bool,
950 SkipWhile::new(self, predicate)
953 /// Creates an iterator that yields elements based on a predicate.
955 /// `take_while()` takes a closure as an argument. It will call this
956 /// closure on each element of the iterator, and yield elements
957 /// while it returns `true`.
959 /// After `false` is returned, `take_while()`'s job is over, and the
960 /// rest of the elements are ignored.
967 /// let a = [-1i32, 0, 1];
969 /// let mut iter = a.iter().take_while(|x| x.is_negative());
971 /// assert_eq!(iter.next(), Some(&-1));
972 /// assert_eq!(iter.next(), None);
975 /// Because the closure passed to `take_while()` takes a reference, and many
976 /// iterators iterate over references, this leads to a possibly confusing
977 /// situation, where the type of the closure is a double reference:
980 /// let a = [-1, 0, 1];
982 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
984 /// assert_eq!(iter.next(), Some(&-1));
985 /// assert_eq!(iter.next(), None);
988 /// Stopping after an initial `false`:
991 /// let a = [-1, 0, 1, -2];
993 /// let mut iter = a.iter().take_while(|x| **x < 0);
995 /// assert_eq!(iter.next(), Some(&-1));
997 /// // We have more elements that are less than zero, but since we already
998 /// // got a false, take_while() isn't used any more
999 /// assert_eq!(iter.next(), None);
1002 /// Because `take_while()` needs to look at the value in order to see if it
1003 /// should be included or not, consuming iterators will see that it is
1007 /// let a = [1, 2, 3, 4];
1008 /// let mut iter = a.iter();
1010 /// let result: Vec<i32> = iter.by_ref()
1011 /// .take_while(|n| **n != 3)
1015 /// assert_eq!(result, &[1, 2]);
1017 /// let result: Vec<i32> = iter.cloned().collect();
1019 /// assert_eq!(result, &[4]);
1022 /// The `3` is no longer there, because it was consumed in order to see if
1023 /// the iteration should stop, but wasn't placed back into the iterator.
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1029 P: FnMut(&Self::Item) -> bool,
1031 TakeWhile::new(self, predicate)
1034 /// Creates an iterator that both yields elements based on a predicate and maps.
1036 /// `map_while()` takes a closure as an argument. It will call this
1037 /// closure on each element of the iterator, and yield elements
1038 /// while it returns [`Some(_)`][`Some`].
1045 /// #![feature(iter_map_while)]
1046 /// let a = [-1i32, 4, 0, 1];
1048 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1050 /// assert_eq!(iter.next(), Some(-16));
1051 /// assert_eq!(iter.next(), Some(4));
1052 /// assert_eq!(iter.next(), None);
1055 /// Here's the same example, but with [`take_while`] and [`map`]:
1057 /// [`take_while`]: #method.take_while
1058 /// [`map`]: #method.map
1061 /// let a = [-1i32, 4, 0, 1];
1063 /// let mut iter = a.iter()
1064 /// .map(|x| 16i32.checked_div(*x))
1065 /// .take_while(|x| x.is_some())
1066 /// .map(|x| x.unwrap());
1068 /// assert_eq!(iter.next(), Some(-16));
1069 /// assert_eq!(iter.next(), Some(4));
1070 /// assert_eq!(iter.next(), None);
1073 /// Stopping after an initial [`None`]:
1076 /// #![feature(iter_map_while)]
1077 /// use std::convert::TryFrom;
1079 /// let a = [0, 1, 2, -3, 4, 5, -6];
1081 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1082 /// let vec = iter.collect::<Vec<_>>();
1084 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1085 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` entcountered.
1086 /// assert_eq!(vec, vec![0, 1, 2]);
1089 /// Because `map_while()` needs to look at the value in order to see if it
1090 /// should be included or not, consuming iterators will see that it is
1094 /// #![feature(iter_map_while)]
1095 /// use std::convert::TryFrom;
1097 /// let a = [1, 2, -3, 4];
1098 /// let mut iter = a.iter();
1100 /// let result: Vec<u32> = iter.by_ref()
1101 /// .map_while(|n| u32::try_from(*n).ok())
1104 /// assert_eq!(result, &[1, 2]);
1106 /// let result: Vec<i32> = iter.cloned().collect();
1108 /// assert_eq!(result, &[4]);
1111 /// The `-3` is no longer there, because it was consumed in order to see if
1112 /// the iteration should stop, but wasn't placed back into the iterator.
1114 /// Note that unlike [`take_while`] this iterator is **not** fused.
1115 /// It is also not specified what this iterator returns after the first` None` is returned.
1116 /// If you need fused iterator, use [`fuse`].
1118 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
1119 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1120 /// [`fuse`]: #method.fuse
1122 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1123 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1126 P: FnMut(Self::Item) -> Option<B>,
1128 MapWhile::new(self, predicate)
1131 /// Creates an iterator that skips the first `n` elements.
1133 /// After they have been consumed, the rest of the elements are yielded.
1134 /// Rather than overriding this method directly, instead override the `nth` method.
1141 /// let a = [1, 2, 3];
1143 /// let mut iter = a.iter().skip(2);
1145 /// assert_eq!(iter.next(), Some(&3));
1146 /// assert_eq!(iter.next(), None);
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 fn skip(self, n: usize) -> Skip<Self>
1157 /// Creates an iterator that yields its first `n` elements.
1164 /// let a = [1, 2, 3];
1166 /// let mut iter = a.iter().take(2);
1168 /// assert_eq!(iter.next(), Some(&1));
1169 /// assert_eq!(iter.next(), Some(&2));
1170 /// assert_eq!(iter.next(), None);
1173 /// `take()` is often used with an infinite iterator, to make it finite:
1176 /// let mut iter = (0..).take(3);
1178 /// assert_eq!(iter.next(), Some(0));
1179 /// assert_eq!(iter.next(), Some(1));
1180 /// assert_eq!(iter.next(), Some(2));
1181 /// assert_eq!(iter.next(), None);
1184 /// If less than `n` elements are available,
1185 /// `take` will limit itself to the size of the underlying iterator:
1188 /// let v = vec![1, 2];
1189 /// let mut iter = v.into_iter().take(5);
1190 /// assert_eq!(iter.next(), Some(1));
1191 /// assert_eq!(iter.next(), Some(2));
1192 /// assert_eq!(iter.next(), None);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 fn take(self, n: usize) -> Take<Self>
1203 /// An iterator adaptor similar to [`fold`] that holds internal state and
1204 /// produces a new iterator.
1206 /// [`fold`]: #method.fold
1208 /// `scan()` takes two arguments: an initial value which seeds the internal
1209 /// state, and a closure with two arguments, the first being a mutable
1210 /// reference to the internal state and the second an iterator element.
1211 /// The closure can assign to the internal state to share state between
1214 /// On iteration, the closure will be applied to each element of the
1215 /// iterator and the return value from the closure, an [`Option`], is
1216 /// yielded by the iterator.
1218 /// [`Option`]: ../../std/option/enum.Option.html
1225 /// let a = [1, 2, 3];
1227 /// let mut iter = a.iter().scan(1, |state, &x| {
1228 /// // each iteration, we'll multiply the state by the element
1229 /// *state = *state * x;
1231 /// // then, we'll yield the negation of the state
1235 /// assert_eq!(iter.next(), Some(-1));
1236 /// assert_eq!(iter.next(), Some(-2));
1237 /// assert_eq!(iter.next(), Some(-6));
1238 /// assert_eq!(iter.next(), None);
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1245 F: FnMut(&mut St, Self::Item) -> Option<B>,
1247 Scan::new(self, initial_state, f)
1250 /// Creates an iterator that works like map, but flattens nested structure.
1252 /// The [`map`] adapter is very useful, but only when the closure
1253 /// argument produces values. If it produces an iterator instead, there's
1254 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1257 /// You can think of `flat_map(f)` as the semantic equivalent
1258 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1260 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1261 /// one item for each element, and `flat_map()`'s closure returns an
1262 /// iterator for each element.
1264 /// [`map`]: #method.map
1265 /// [`flatten`]: #method.flatten
1272 /// let words = ["alpha", "beta", "gamma"];
1274 /// // chars() returns an iterator
1275 /// let merged: String = words.iter()
1276 /// .flat_map(|s| s.chars())
1278 /// assert_eq!(merged, "alphabetagamma");
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1286 F: FnMut(Self::Item) -> U,
1288 FlatMap::new(self, f)
1291 /// Creates an iterator that flattens nested structure.
1293 /// This is useful when you have an iterator of iterators or an iterator of
1294 /// things that can be turned into iterators and you want to remove one
1295 /// level of indirection.
1302 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1303 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1304 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1307 /// Mapping and then flattening:
1310 /// let words = ["alpha", "beta", "gamma"];
1312 /// // chars() returns an iterator
1313 /// let merged: String = words.iter()
1314 /// .map(|s| s.chars())
1317 /// assert_eq!(merged, "alphabetagamma");
1320 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1321 /// in this case since it conveys intent more clearly:
1324 /// let words = ["alpha", "beta", "gamma"];
1326 /// // chars() returns an iterator
1327 /// let merged: String = words.iter()
1328 /// .flat_map(|s| s.chars())
1330 /// assert_eq!(merged, "alphabetagamma");
1333 /// Flattening once only removes one level of nesting:
1336 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1338 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1339 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1341 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1342 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1345 /// Here we see that `flatten()` does not perform a "deep" flatten.
1346 /// Instead, only one level of nesting is removed. That is, if you
1347 /// `flatten()` a three-dimensional array the result will be
1348 /// two-dimensional and not one-dimensional. To get a one-dimensional
1349 /// structure, you have to `flatten()` again.
1351 /// [`flat_map()`]: #method.flat_map
1353 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1354 fn flatten(self) -> Flatten<Self>
1357 Self::Item: IntoIterator,
1362 /// Creates an iterator which ends after the first [`None`].
1364 /// After an iterator returns [`None`], future calls may or may not yield
1365 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1366 /// [`None`] is given, it will always return [`None`] forever.
1368 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1369 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1376 /// // an iterator which alternates between Some and None
1377 /// struct Alternate {
1381 /// impl Iterator for Alternate {
1382 /// type Item = i32;
1384 /// fn next(&mut self) -> Option<i32> {
1385 /// let val = self.state;
1386 /// self.state = self.state + 1;
1388 /// // if it's even, Some(i32), else None
1389 /// if val % 2 == 0 {
1397 /// let mut iter = Alternate { state: 0 };
1399 /// // we can see our iterator going back and forth
1400 /// assert_eq!(iter.next(), Some(0));
1401 /// assert_eq!(iter.next(), None);
1402 /// assert_eq!(iter.next(), Some(2));
1403 /// assert_eq!(iter.next(), None);
1405 /// // however, once we fuse it...
1406 /// let mut iter = iter.fuse();
1408 /// assert_eq!(iter.next(), Some(4));
1409 /// assert_eq!(iter.next(), None);
1411 /// // it will always return `None` after the first time.
1412 /// assert_eq!(iter.next(), None);
1413 /// assert_eq!(iter.next(), None);
1414 /// assert_eq!(iter.next(), None);
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 fn fuse(self) -> Fuse<Self>
1425 /// Does something with each element of an iterator, passing the value on.
1427 /// When using iterators, you'll often chain several of them together.
1428 /// While working on such code, you might want to check out what's
1429 /// happening at various parts in the pipeline. To do that, insert
1430 /// a call to `inspect()`.
1432 /// It's more common for `inspect()` to be used as a debugging tool than to
1433 /// exist in your final code, but applications may find it useful in certain
1434 /// situations when errors need to be logged before being discarded.
1441 /// let a = [1, 4, 2, 3];
1443 /// // this iterator sequence is complex.
1444 /// let sum = a.iter()
1446 /// .filter(|x| x % 2 == 0)
1447 /// .fold(0, |sum, i| sum + i);
1449 /// println!("{}", sum);
1451 /// // let's add some inspect() calls to investigate what's happening
1452 /// let sum = a.iter()
1454 /// .inspect(|x| println!("about to filter: {}", x))
1455 /// .filter(|x| x % 2 == 0)
1456 /// .inspect(|x| println!("made it through filter: {}", x))
1457 /// .fold(0, |sum, i| sum + i);
1459 /// println!("{}", sum);
1462 /// This will print:
1466 /// about to filter: 1
1467 /// about to filter: 4
1468 /// made it through filter: 4
1469 /// about to filter: 2
1470 /// made it through filter: 2
1471 /// about to filter: 3
1475 /// Logging errors before discarding them:
1478 /// let lines = ["1", "2", "a"];
1480 /// let sum: i32 = lines
1482 /// .map(|line| line.parse::<i32>())
1483 /// .inspect(|num| {
1484 /// if let Err(ref e) = *num {
1485 /// println!("Parsing error: {}", e);
1488 /// .filter_map(Result::ok)
1491 /// println!("Sum: {}", sum);
1494 /// This will print:
1497 /// Parsing error: invalid digit found in string
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1505 F: FnMut(&Self::Item),
1507 Inspect::new(self, f)
1510 /// Borrows an iterator, rather than consuming it.
1512 /// This is useful to allow applying iterator adaptors while still
1513 /// retaining ownership of the original iterator.
1520 /// let a = [1, 2, 3];
1522 /// let iter = a.iter();
1524 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1526 /// assert_eq!(sum, 6);
1528 /// // if we try to use iter again, it won't work. The following line
1529 /// // gives "error: use of moved value: `iter`
1530 /// // assert_eq!(iter.next(), None);
1532 /// // let's try that again
1533 /// let a = [1, 2, 3];
1535 /// let mut iter = a.iter();
1537 /// // instead, we add in a .by_ref()
1538 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1540 /// assert_eq!(sum, 3);
1542 /// // now this is just fine:
1543 /// assert_eq!(iter.next(), Some(&3));
1544 /// assert_eq!(iter.next(), None);
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 fn by_ref(&mut self) -> &mut Self
1554 /// Transforms an iterator into a collection.
1556 /// `collect()` can take anything iterable, and turn it into a relevant
1557 /// collection. This is one of the more powerful methods in the standard
1558 /// library, used in a variety of contexts.
1560 /// The most basic pattern in which `collect()` is used is to turn one
1561 /// collection into another. You take a collection, call [`iter`] on it,
1562 /// do a bunch of transformations, and then `collect()` at the end.
1564 /// One of the keys to `collect()`'s power is that many things you might
1565 /// not think of as 'collections' actually are. For example, a [`String`]
1566 /// is a collection of [`char`]s. And a collection of
1567 /// [`Result<T, E>`][`Result`] can be thought of as single
1568 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1570 /// Because `collect()` is so general, it can cause problems with type
1571 /// inference. As such, `collect()` is one of the few times you'll see
1572 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1573 /// helps the inference algorithm understand specifically which collection
1574 /// you're trying to collect into.
1581 /// let a = [1, 2, 3];
1583 /// let doubled: Vec<i32> = a.iter()
1584 /// .map(|&x| x * 2)
1587 /// assert_eq!(vec![2, 4, 6], doubled);
1590 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1591 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1593 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1596 /// use std::collections::VecDeque;
1598 /// let a = [1, 2, 3];
1600 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1602 /// assert_eq!(2, doubled[0]);
1603 /// assert_eq!(4, doubled[1]);
1604 /// assert_eq!(6, doubled[2]);
1607 /// Using the 'turbofish' instead of annotating `doubled`:
1610 /// let a = [1, 2, 3];
1612 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1614 /// assert_eq!(vec![2, 4, 6], doubled);
1617 /// Because `collect()` only cares about what you're collecting into, you can
1618 /// still use a partial type hint, `_`, with the turbofish:
1621 /// let a = [1, 2, 3];
1623 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1625 /// assert_eq!(vec![2, 4, 6], doubled);
1628 /// Using `collect()` to make a [`String`]:
1631 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1633 /// let hello: String = chars.iter()
1634 /// .map(|&x| x as u8)
1635 /// .map(|x| (x + 1) as char)
1638 /// assert_eq!("hello", hello);
1641 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1642 /// see if any of them failed:
1645 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1647 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1649 /// // gives us the first error
1650 /// assert_eq!(Err("nope"), result);
1652 /// let results = [Ok(1), Ok(3)];
1654 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1656 /// // gives us the list of answers
1657 /// assert_eq!(Ok(vec![1, 3]), result);
1660 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1661 /// [`String`]: ../../std/string/struct.String.html
1662 /// [`char`]: ../../std/primitive.char.html
1663 /// [`Result`]: ../../std/result/enum.Result.html
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1667 fn collect<B: FromIterator<Self::Item>>(self) -> B
1671 FromIterator::from_iter(self)
1674 /// Consumes an iterator, creating two collections from it.
1676 /// The predicate passed to `partition()` can return `true`, or `false`.
1677 /// `partition()` returns a pair, all of the elements for which it returned
1678 /// `true`, and all of the elements for which it returned `false`.
1680 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1682 /// [`is_partitioned()`]: #method.is_partitioned
1683 /// [`partition_in_place()`]: #method.partition_in_place
1690 /// let a = [1, 2, 3];
1692 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1694 /// .partition(|&n| n % 2 == 0);
1696 /// assert_eq!(even, vec![2]);
1697 /// assert_eq!(odd, vec![1, 3]);
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 fn partition<B, F>(self, f: F) -> (B, B)
1703 B: Default + Extend<Self::Item>,
1704 F: FnMut(&Self::Item) -> bool,
1707 fn extend<'a, T, B: Extend<T>>(
1708 mut f: impl FnMut(&T) -> bool + 'a,
1711 ) -> impl FnMut((), T) + 'a {
1716 right.extend_one(x);
1721 let mut left: B = Default::default();
1722 let mut right: B = Default::default();
1724 self.fold((), extend(f, &mut left, &mut right));
1729 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1730 /// such that all those that return `true` precede all those that return `false`.
1731 /// Returns the number of `true` elements found.
1733 /// The relative order of partitioned items is not maintained.
1735 /// See also [`is_partitioned()`] and [`partition()`].
1737 /// [`is_partitioned()`]: #method.is_partitioned
1738 /// [`partition()`]: #method.partition
1743 /// #![feature(iter_partition_in_place)]
1745 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1747 /// // Partition in-place between evens and odds
1748 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1750 /// assert_eq!(i, 3);
1751 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1752 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1754 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1755 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1757 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1758 P: FnMut(&T) -> bool,
1760 // FIXME: should we worry about the count overflowing? The only way to have more than
1761 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1763 // These closure "factory" functions exist to avoid genericity in `Self`.
1767 predicate: &'a mut impl FnMut(&T) -> bool,
1768 true_count: &'a mut usize,
1769 ) -> impl FnMut(&&mut T) -> bool + 'a {
1771 let p = predicate(&**x);
1772 *true_count += p as usize;
1778 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1779 move |x| predicate(&**x)
1782 // Repeatedly find the first `false` and swap it with the last `true`.
1783 let mut true_count = 0;
1784 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1785 if let Some(tail) = self.rfind(is_true(predicate)) {
1786 crate::mem::swap(head, tail);
1795 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1796 /// such that all those that return `true` precede all those that return `false`.
1798 /// See also [`partition()`] and [`partition_in_place()`].
1800 /// [`partition()`]: #method.partition
1801 /// [`partition_in_place()`]: #method.partition_in_place
1806 /// #![feature(iter_is_partitioned)]
1808 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1809 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1811 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1812 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1815 P: FnMut(Self::Item) -> bool,
1817 // Either all items test `true`, or the first clause stops at `false`
1818 // and we check that there are no more `true` items after that.
1819 self.all(&mut predicate) || !self.any(predicate)
1822 /// An iterator method that applies a function as long as it returns
1823 /// successfully, producing a single, final value.
1825 /// `try_fold()` takes two arguments: an initial value, and a closure with
1826 /// two arguments: an 'accumulator', and an element. The closure either
1827 /// returns successfully, with the value that the accumulator should have
1828 /// for the next iteration, or it returns failure, with an error value that
1829 /// is propagated back to the caller immediately (short-circuiting).
1831 /// The initial value is the value the accumulator will have on the first
1832 /// call. If applying the closure succeeded against every element of the
1833 /// iterator, `try_fold()` returns the final accumulator as success.
1835 /// Folding is useful whenever you have a collection of something, and want
1836 /// to produce a single value from it.
1838 /// # Note to Implementors
1840 /// Several of the other (forward) methods have default implementations in
1841 /// terms of this one, so try to implement this explicitly if it can
1842 /// do something better than the default `for` loop implementation.
1844 /// In particular, try to have this call `try_fold()` on the internal parts
1845 /// from which this iterator is composed. If multiple calls are needed,
1846 /// the `?` operator may be convenient for chaining the accumulator value
1847 /// along, but beware any invariants that need to be upheld before those
1848 /// early returns. This is a `&mut self` method, so iteration needs to be
1849 /// resumable after hitting an error here.
1856 /// let a = [1, 2, 3];
1858 /// // the checked sum of all of the elements of the array
1859 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1861 /// assert_eq!(sum, Some(6));
1864 /// Short-circuiting:
1867 /// let a = [10, 20, 30, 100, 40, 50];
1868 /// let mut it = a.iter();
1870 /// // This sum overflows when adding the 100 element
1871 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1872 /// assert_eq!(sum, None);
1874 /// // Because it short-circuited, the remaining elements are still
1875 /// // available through the iterator.
1876 /// assert_eq!(it.len(), 2);
1877 /// assert_eq!(it.next(), Some(&40));
1880 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1881 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1884 F: FnMut(B, Self::Item) -> R,
1887 let mut accum = init;
1888 while let Some(x) = self.next() {
1889 accum = f(accum, x)?;
1894 /// An iterator method that applies a fallible function to each item in the
1895 /// iterator, stopping at the first error and returning that error.
1897 /// This can also be thought of as the fallible form of [`for_each()`]
1898 /// or as the stateless version of [`try_fold()`].
1900 /// [`for_each()`]: #method.for_each
1901 /// [`try_fold()`]: #method.try_fold
1906 /// use std::fs::rename;
1907 /// use std::io::{stdout, Write};
1908 /// use std::path::Path;
1910 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1912 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1913 /// assert!(res.is_ok());
1915 /// let mut it = data.iter().cloned();
1916 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1917 /// assert!(res.is_err());
1918 /// // It short-circuited, so the remaining items are still in the iterator:
1919 /// assert_eq!(it.next(), Some("stale_bread.json"));
1922 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1923 fn try_for_each<F, R>(&mut self, f: F) -> R
1926 F: FnMut(Self::Item) -> R,
1930 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
1934 self.try_fold((), call(f))
1937 /// An iterator method that applies a function, producing a single, final value.
1939 /// `fold()` takes two arguments: an initial value, and a closure with two
1940 /// arguments: an 'accumulator', and an element. The closure returns the value that
1941 /// the accumulator should have for the next iteration.
1943 /// The initial value is the value the accumulator will have on the first
1946 /// After applying this closure to every element of the iterator, `fold()`
1947 /// returns the accumulator.
1949 /// This operation is sometimes called 'reduce' or 'inject'.
1951 /// Folding is useful whenever you have a collection of something, and want
1952 /// to produce a single value from it.
1954 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1955 /// may not terminate for infinite iterators, even on traits for which a
1956 /// result is determinable in finite time.
1958 /// # Note to Implementors
1960 /// Several of the other (forward) methods have default implementations in
1961 /// terms of this one, so try to implement this explicitly if it can
1962 /// do something better than the default `for` loop implementation.
1964 /// In particular, try to have this call `fold()` on the internal parts
1965 /// from which this iterator is composed.
1972 /// let a = [1, 2, 3];
1974 /// // the sum of all of the elements of the array
1975 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1977 /// assert_eq!(sum, 6);
1980 /// Let's walk through each step of the iteration here:
1982 /// | element | acc | x | result |
1983 /// |---------|-----|---|--------|
1985 /// | 1 | 0 | 1 | 1 |
1986 /// | 2 | 1 | 2 | 3 |
1987 /// | 3 | 3 | 3 | 6 |
1989 /// And so, our final result, `6`.
1991 /// It's common for people who haven't used iterators a lot to
1992 /// use a `for` loop with a list of things to build up a result. Those
1993 /// can be turned into `fold()`s:
1995 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1998 /// let numbers = [1, 2, 3, 4, 5];
2000 /// let mut result = 0;
2003 /// for i in &numbers {
2004 /// result = result + i;
2008 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2010 /// // they're the same
2011 /// assert_eq!(result, result2);
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2018 F: FnMut(B, Self::Item) -> B,
2020 let mut accum = init;
2021 while let Some(x) = self.next() {
2022 accum = f(accum, x);
2027 /// The same as [`fold()`](#method.fold), but uses the first element in the
2028 /// iterator as the initial value, folding every subsequent element into it.
2029 /// If the iterator is empty, return `None`; otherwise, return the result
2034 /// Find the maximum value:
2037 /// #![feature(iterator_fold_self)]
2039 /// fn find_max<I>(iter: I) -> Option<I::Item>
2040 /// where I: Iterator,
2043 /// iter.fold_first(|a, b| {
2044 /// if a >= b { a } else { b }
2047 /// let a = [10, 20, 5, -23, 0];
2048 /// let b: [u32; 0] = [];
2050 /// assert_eq!(find_max(a.iter()), Some(&20));
2051 /// assert_eq!(find_max(b.iter()), None);
2054 #[unstable(feature = "iterator_fold_self", issue = "68125")]
2055 fn fold_first<F>(mut self, f: F) -> Option<Self::Item>
2058 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2060 let first = self.next()?;
2061 Some(self.fold(first, f))
2064 /// Tests if every element of the iterator matches a predicate.
2066 /// `all()` takes a closure that returns `true` or `false`. It applies
2067 /// this closure to each element of the iterator, and if they all return
2068 /// `true`, then so does `all()`. If any of them return `false`, it
2069 /// returns `false`.
2071 /// `all()` is short-circuiting; in other words, it will stop processing
2072 /// as soon as it finds a `false`, given that no matter what else happens,
2073 /// the result will also be `false`.
2075 /// An empty iterator returns `true`.
2082 /// let a = [1, 2, 3];
2084 /// assert!(a.iter().all(|&x| x > 0));
2086 /// assert!(!a.iter().all(|&x| x > 2));
2089 /// Stopping at the first `false`:
2092 /// let a = [1, 2, 3];
2094 /// let mut iter = a.iter();
2096 /// assert!(!iter.all(|&x| x != 2));
2098 /// // we can still use `iter`, as there are more elements.
2099 /// assert_eq!(iter.next(), Some(&3));
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 fn all<F>(&mut self, f: F) -> bool
2106 F: FnMut(Self::Item) -> bool,
2109 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2111 if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) }
2114 self.try_fold((), check(f)) == LoopState::Continue(())
2117 /// Tests if any element of the iterator matches a predicate.
2119 /// `any()` takes a closure that returns `true` or `false`. It applies
2120 /// this closure to each element of the iterator, and if any of them return
2121 /// `true`, then so does `any()`. If they all return `false`, it
2122 /// returns `false`.
2124 /// `any()` is short-circuiting; in other words, it will stop processing
2125 /// as soon as it finds a `true`, given that no matter what else happens,
2126 /// the result will also be `true`.
2128 /// An empty iterator returns `false`.
2135 /// let a = [1, 2, 3];
2137 /// assert!(a.iter().any(|&x| x > 0));
2139 /// assert!(!a.iter().any(|&x| x > 5));
2142 /// Stopping at the first `true`:
2145 /// let a = [1, 2, 3];
2147 /// let mut iter = a.iter();
2149 /// assert!(iter.any(|&x| x != 2));
2151 /// // we can still use `iter`, as there are more elements.
2152 /// assert_eq!(iter.next(), Some(&2));
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 fn any<F>(&mut self, f: F) -> bool
2159 F: FnMut(Self::Item) -> bool,
2162 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2164 if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) }
2168 self.try_fold((), check(f)) == LoopState::Break(())
2171 /// Searches for an element of an iterator that satisfies a predicate.
2173 /// `find()` takes a closure that returns `true` or `false`. It applies
2174 /// this closure to each element of the iterator, and if any of them return
2175 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2176 /// `false`, it returns [`None`].
2178 /// `find()` is short-circuiting; in other words, it will stop processing
2179 /// as soon as the closure returns `true`.
2181 /// Because `find()` takes a reference, and many iterators iterate over
2182 /// references, this leads to a possibly confusing situation where the
2183 /// argument is a double reference. You can see this effect in the
2184 /// examples below, with `&&x`.
2186 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
2187 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2194 /// let a = [1, 2, 3];
2196 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2198 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2201 /// Stopping at the first `true`:
2204 /// let a = [1, 2, 3];
2206 /// let mut iter = a.iter();
2208 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2210 /// // we can still use `iter`, as there are more elements.
2211 /// assert_eq!(iter.next(), Some(&3));
2214 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2216 #[stable(feature = "rust1", since = "1.0.0")]
2217 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2220 P: FnMut(&Self::Item) -> bool,
2224 mut predicate: impl FnMut(&T) -> bool,
2225 ) -> impl FnMut((), T) -> LoopState<(), T> {
2227 if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) }
2231 self.try_fold((), check(predicate)).break_value()
2234 /// Applies function to the elements of iterator and returns
2235 /// the first non-none result.
2237 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2243 /// let a = ["lol", "NaN", "2", "5"];
2245 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2247 /// assert_eq!(first_number, Some(2));
2250 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2251 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2254 F: FnMut(Self::Item) -> Option<B>,
2257 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> LoopState<(), B> {
2258 move |(), x| match f(x) {
2259 Some(x) => LoopState::Break(x),
2260 None => LoopState::Continue(()),
2264 self.try_fold((), check(f)).break_value()
2267 /// Applies function to the elements of iterator and returns
2268 /// the first true result or the first error.
2273 /// #![feature(try_find)]
2275 /// let a = ["1", "2", "lol", "NaN", "5"];
2277 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2278 /// Ok(s.parse::<i32>()? == search)
2281 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2282 /// assert_eq!(result, Ok(Some(&"2")));
2284 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2285 /// assert!(result.is_err());
2288 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2289 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2292 F: FnMut(&Self::Item) -> R,
2296 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> LoopState<(), Result<T, R::Error>>
2301 move |(), x| match f(&x).into_result() {
2302 Ok(false) => LoopState::Continue(()),
2303 Ok(true) => LoopState::Break(Ok(x)),
2304 Err(x) => LoopState::Break(Err(x)),
2308 self.try_fold((), check(f)).break_value().transpose()
2311 /// Searches for an element in an iterator, returning its index.
2313 /// `position()` takes a closure that returns `true` or `false`. It applies
2314 /// this closure to each element of the iterator, and if one of them
2315 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2316 /// them return `false`, it returns [`None`].
2318 /// `position()` is short-circuiting; in other words, it will stop
2319 /// processing as soon as it finds a `true`.
2321 /// # Overflow Behavior
2323 /// The method does no guarding against overflows, so if there are more
2324 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2325 /// result or panics. If debug assertions are enabled, a panic is
2330 /// This function might panic if the iterator has more than `usize::MAX`
2331 /// non-matching elements.
2333 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2334 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2335 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
2342 /// let a = [1, 2, 3];
2344 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2346 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2349 /// Stopping at the first `true`:
2352 /// let a = [1, 2, 3, 4];
2354 /// let mut iter = a.iter();
2356 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2358 /// // we can still use `iter`, as there are more elements.
2359 /// assert_eq!(iter.next(), Some(&3));
2361 /// // The returned index depends on iterator state
2362 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2366 #[stable(feature = "rust1", since = "1.0.0")]
2367 fn position<P>(&mut self, predicate: P) -> Option<usize>
2370 P: FnMut(Self::Item) -> bool,
2374 mut predicate: impl FnMut(T) -> bool,
2375 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2376 // The addition might panic on overflow
2378 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) }
2382 self.try_fold(0, check(predicate)).break_value()
2385 /// Searches for an element in an iterator from the right, returning its
2388 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2389 /// this closure to each element of the iterator, starting from the end,
2390 /// and if one of them returns `true`, then `rposition()` returns
2391 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2393 /// `rposition()` is short-circuiting; in other words, it will stop
2394 /// processing as soon as it finds a `true`.
2396 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2397 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2404 /// let a = [1, 2, 3];
2406 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2408 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2411 /// Stopping at the first `true`:
2414 /// let a = [1, 2, 3];
2416 /// let mut iter = a.iter();
2418 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2420 /// // we can still use `iter`, as there are more elements.
2421 /// assert_eq!(iter.next(), Some(&1));
2424 #[stable(feature = "rust1", since = "1.0.0")]
2425 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2427 P: FnMut(Self::Item) -> bool,
2428 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2430 // No need for an overflow check here, because `ExactSizeIterator`
2431 // implies that the number of elements fits into a `usize`.
2434 mut predicate: impl FnMut(T) -> bool,
2435 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2438 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) }
2443 self.try_rfold(n, check(predicate)).break_value()
2446 /// Returns the maximum element of an iterator.
2448 /// If several elements are equally maximum, the last element is
2449 /// returned. If the iterator is empty, [`None`] is returned.
2451 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2458 /// let a = [1, 2, 3];
2459 /// let b: Vec<u32> = Vec::new();
2461 /// assert_eq!(a.iter().max(), Some(&3));
2462 /// assert_eq!(b.iter().max(), None);
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 fn max(self) -> Option<Self::Item>
2471 self.max_by(Ord::cmp)
2474 /// Returns the minimum element of an iterator.
2476 /// If several elements are equally minimum, the first element is
2477 /// returned. If the iterator is empty, [`None`] is returned.
2479 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2486 /// let a = [1, 2, 3];
2487 /// let b: Vec<u32> = Vec::new();
2489 /// assert_eq!(a.iter().min(), Some(&1));
2490 /// assert_eq!(b.iter().min(), None);
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 fn min(self) -> Option<Self::Item>
2499 self.min_by(Ord::cmp)
2502 /// Returns the element that gives the maximum value from the
2503 /// specified function.
2505 /// If several elements are equally maximum, the last element is
2506 /// returned. If the iterator is empty, [`None`] is returned.
2508 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2513 /// let a = [-3_i32, 0, 1, 5, -10];
2514 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2517 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2518 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2521 F: FnMut(&Self::Item) -> B,
2524 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2529 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2533 let (_, x) = self.map(key(f)).max_by(compare)?;
2537 /// Returns the element that gives the maximum value with respect to the
2538 /// specified comparison function.
2540 /// If several elements are equally maximum, the last element is
2541 /// returned. If the iterator is empty, [`None`] is returned.
2543 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2548 /// let a = [-3_i32, 0, 1, 5, -10];
2549 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2552 #[stable(feature = "iter_max_by", since = "1.15.0")]
2553 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2556 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2559 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2560 move |x, y| cmp::max_by(x, y, &mut compare)
2563 self.fold_first(fold(compare))
2566 /// Returns the element that gives the minimum value from the
2567 /// specified function.
2569 /// If several elements are equally minimum, the first element is
2570 /// returned. If the iterator is empty, [`None`] is returned.
2572 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2577 /// let a = [-3_i32, 0, 1, 5, -10];
2578 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2581 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2582 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2585 F: FnMut(&Self::Item) -> B,
2588 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2593 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2597 let (_, x) = self.map(key(f)).min_by(compare)?;
2601 /// Returns the element that gives the minimum value with respect to the
2602 /// specified comparison function.
2604 /// If several elements are equally minimum, the first element is
2605 /// returned. If the iterator is empty, [`None`] is returned.
2607 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2612 /// let a = [-3_i32, 0, 1, 5, -10];
2613 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2616 #[stable(feature = "iter_min_by", since = "1.15.0")]
2617 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2620 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2623 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2624 move |x, y| cmp::min_by(x, y, &mut compare)
2627 self.fold_first(fold(compare))
2630 /// Reverses an iterator's direction.
2632 /// Usually, iterators iterate from left to right. After using `rev()`,
2633 /// an iterator will instead iterate from right to left.
2635 /// This is only possible if the iterator has an end, so `rev()` only
2636 /// works on [`DoubleEndedIterator`]s.
2638 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2643 /// let a = [1, 2, 3];
2645 /// let mut iter = a.iter().rev();
2647 /// assert_eq!(iter.next(), Some(&3));
2648 /// assert_eq!(iter.next(), Some(&2));
2649 /// assert_eq!(iter.next(), Some(&1));
2651 /// assert_eq!(iter.next(), None);
2654 #[stable(feature = "rust1", since = "1.0.0")]
2655 fn rev(self) -> Rev<Self>
2657 Self: Sized + DoubleEndedIterator,
2662 /// Converts an iterator of pairs into a pair of containers.
2664 /// `unzip()` consumes an entire iterator of pairs, producing two
2665 /// collections: one from the left elements of the pairs, and one
2666 /// from the right elements.
2668 /// This function is, in some sense, the opposite of [`zip`].
2670 /// [`zip`]: #method.zip
2677 /// let a = [(1, 2), (3, 4)];
2679 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2681 /// assert_eq!(left, [1, 3]);
2682 /// assert_eq!(right, [2, 4]);
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2687 FromA: Default + Extend<A>,
2688 FromB: Default + Extend<B>,
2689 Self: Sized + Iterator<Item = (A, B)>,
2691 fn extend<'a, A, B>(
2692 ts: &'a mut impl Extend<A>,
2693 us: &'a mut impl Extend<B>,
2694 ) -> impl FnMut((), (A, B)) + 'a {
2701 let mut ts: FromA = Default::default();
2702 let mut us: FromB = Default::default();
2704 let (lower_bound, _) = self.size_hint();
2705 if lower_bound > 0 {
2706 ts.extend_reserve(lower_bound);
2707 us.extend_reserve(lower_bound);
2710 self.fold((), extend(&mut ts, &mut us));
2715 /// Creates an iterator which copies all of its elements.
2717 /// This is useful when you have an iterator over `&T`, but you need an
2718 /// iterator over `T`.
2725 /// let a = [1, 2, 3];
2727 /// let v_copied: Vec<_> = a.iter().copied().collect();
2729 /// // copied is the same as .map(|&x| x)
2730 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2732 /// assert_eq!(v_copied, vec![1, 2, 3]);
2733 /// assert_eq!(v_map, vec![1, 2, 3]);
2735 #[stable(feature = "iter_copied", since = "1.36.0")]
2736 fn copied<'a, T: 'a>(self) -> Copied<Self>
2738 Self: Sized + Iterator<Item = &'a T>,
2744 /// Creates an iterator which [`clone`]s all of its elements.
2746 /// This is useful when you have an iterator over `&T`, but you need an
2747 /// iterator over `T`.
2749 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2756 /// let a = [1, 2, 3];
2758 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2760 /// // cloned is the same as .map(|&x| x), for integers
2761 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2763 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2764 /// assert_eq!(v_map, vec![1, 2, 3]);
2766 #[stable(feature = "rust1", since = "1.0.0")]
2767 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2769 Self: Sized + Iterator<Item = &'a T>,
2775 /// Repeats an iterator endlessly.
2777 /// Instead of stopping at [`None`], the iterator will instead start again,
2778 /// from the beginning. After iterating again, it will start at the
2779 /// beginning again. And again. And again. Forever.
2781 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2788 /// let a = [1, 2, 3];
2790 /// let mut it = a.iter().cycle();
2792 /// assert_eq!(it.next(), Some(&1));
2793 /// assert_eq!(it.next(), Some(&2));
2794 /// assert_eq!(it.next(), Some(&3));
2795 /// assert_eq!(it.next(), Some(&1));
2796 /// assert_eq!(it.next(), Some(&2));
2797 /// assert_eq!(it.next(), Some(&3));
2798 /// assert_eq!(it.next(), Some(&1));
2800 #[stable(feature = "rust1", since = "1.0.0")]
2802 fn cycle(self) -> Cycle<Self>
2804 Self: Sized + Clone,
2809 /// Sums the elements of an iterator.
2811 /// Takes each element, adds them together, and returns the result.
2813 /// An empty iterator returns the zero value of the type.
2817 /// When calling `sum()` and a primitive integer type is being returned, this
2818 /// method will panic if the computation overflows and debug assertions are
2826 /// let a = [1, 2, 3];
2827 /// let sum: i32 = a.iter().sum();
2829 /// assert_eq!(sum, 6);
2831 #[stable(feature = "iter_arith", since = "1.11.0")]
2832 fn sum<S>(self) -> S
2840 /// Iterates over the entire iterator, multiplying all the elements
2842 /// An empty iterator returns the one value of the type.
2846 /// When calling `product()` and a primitive integer type is being returned,
2847 /// method will panic if the computation overflows and debug assertions are
2853 /// fn factorial(n: u32) -> u32 {
2854 /// (1..=n).product()
2856 /// assert_eq!(factorial(0), 1);
2857 /// assert_eq!(factorial(1), 1);
2858 /// assert_eq!(factorial(5), 120);
2860 #[stable(feature = "iter_arith", since = "1.11.0")]
2861 fn product<P>(self) -> P
2864 P: Product<Self::Item>,
2866 Product::product(self)
2869 /// Lexicographically compares the elements of this `Iterator` with those
2875 /// use std::cmp::Ordering;
2877 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2878 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2879 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2881 #[stable(feature = "iter_order", since = "1.5.0")]
2882 fn cmp<I>(self, other: I) -> Ordering
2884 I: IntoIterator<Item = Self::Item>,
2888 self.cmp_by(other, |x, y| x.cmp(&y))
2891 /// Lexicographically compares the elements of this `Iterator` with those
2892 /// of another with respect to the specified comparison function.
2899 /// #![feature(iter_order_by)]
2901 /// use std::cmp::Ordering;
2903 /// let xs = [1, 2, 3, 4];
2904 /// let ys = [1, 4, 9, 16];
2906 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2907 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2908 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2910 #[unstable(feature = "iter_order_by", issue = "64295")]
2911 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
2915 F: FnMut(Self::Item, I::Item) -> Ordering,
2917 let mut other = other.into_iter();
2920 let x = match self.next() {
2922 if other.next().is_none() {
2923 return Ordering::Equal;
2925 return Ordering::Less;
2931 let y = match other.next() {
2932 None => return Ordering::Greater,
2937 Ordering::Equal => (),
2938 non_eq => return non_eq,
2943 /// Lexicographically compares the elements of this `Iterator` with those
2949 /// use std::cmp::Ordering;
2951 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2952 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2953 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2955 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2957 #[stable(feature = "iter_order", since = "1.5.0")]
2958 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
2961 Self::Item: PartialOrd<I::Item>,
2964 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
2967 /// Lexicographically compares the elements of this `Iterator` with those
2968 /// of another with respect to the specified comparison function.
2975 /// #![feature(iter_order_by)]
2977 /// use std::cmp::Ordering;
2979 /// let xs = [1.0, 2.0, 3.0, 4.0];
2980 /// let ys = [1.0, 4.0, 9.0, 16.0];
2983 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2984 /// Some(Ordering::Less)
2987 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2988 /// Some(Ordering::Equal)
2991 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2992 /// Some(Ordering::Greater)
2995 #[unstable(feature = "iter_order_by", issue = "64295")]
2996 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3000 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3002 let mut other = other.into_iter();
3005 let x = match self.next() {
3007 if other.next().is_none() {
3008 return Some(Ordering::Equal);
3010 return Some(Ordering::Less);
3016 let y = match other.next() {
3017 None => return Some(Ordering::Greater),
3021 match partial_cmp(x, y) {
3022 Some(Ordering::Equal) => (),
3023 non_eq => return non_eq,
3028 /// Determines if the elements of this `Iterator` are equal to those of
3034 /// assert_eq!([1].iter().eq([1].iter()), true);
3035 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3037 #[stable(feature = "iter_order", since = "1.5.0")]
3038 fn eq<I>(self, other: I) -> bool
3041 Self::Item: PartialEq<I::Item>,
3044 self.eq_by(other, |x, y| x == y)
3047 /// Determines if the elements of this `Iterator` are equal to those of
3048 /// another with respect to the specified equality function.
3055 /// #![feature(iter_order_by)]
3057 /// let xs = [1, 2, 3, 4];
3058 /// let ys = [1, 4, 9, 16];
3060 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3062 #[unstable(feature = "iter_order_by", issue = "64295")]
3063 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3067 F: FnMut(Self::Item, I::Item) -> bool,
3069 let mut other = other.into_iter();
3072 let x = match self.next() {
3073 None => return other.next().is_none(),
3077 let y = match other.next() {
3078 None => return false,
3088 /// Determines if the elements of this `Iterator` are unequal to those of
3094 /// assert_eq!([1].iter().ne([1].iter()), false);
3095 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3097 #[stable(feature = "iter_order", since = "1.5.0")]
3098 fn ne<I>(self, other: I) -> bool
3101 Self::Item: PartialEq<I::Item>,
3107 /// Determines if the elements of this `Iterator` are lexicographically
3108 /// less than those of another.
3113 /// assert_eq!([1].iter().lt([1].iter()), false);
3114 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3115 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3117 #[stable(feature = "iter_order", since = "1.5.0")]
3118 fn lt<I>(self, other: I) -> bool
3121 Self::Item: PartialOrd<I::Item>,
3124 self.partial_cmp(other) == Some(Ordering::Less)
3127 /// Determines if the elements of this `Iterator` are lexicographically
3128 /// less or equal to those of another.
3133 /// assert_eq!([1].iter().le([1].iter()), true);
3134 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3135 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3137 #[stable(feature = "iter_order", since = "1.5.0")]
3138 fn le<I>(self, other: I) -> bool
3141 Self::Item: PartialOrd<I::Item>,
3144 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3147 /// Determines if the elements of this `Iterator` are lexicographically
3148 /// greater than those of another.
3153 /// assert_eq!([1].iter().gt([1].iter()), false);
3154 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3155 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3157 #[stable(feature = "iter_order", since = "1.5.0")]
3158 fn gt<I>(self, other: I) -> bool
3161 Self::Item: PartialOrd<I::Item>,
3164 self.partial_cmp(other) == Some(Ordering::Greater)
3167 /// Determines if the elements of this `Iterator` are lexicographically
3168 /// greater than or equal to those of another.
3173 /// assert_eq!([1].iter().ge([1].iter()), true);
3174 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3175 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3177 #[stable(feature = "iter_order", since = "1.5.0")]
3178 fn ge<I>(self, other: I) -> bool
3181 Self::Item: PartialOrd<I::Item>,
3184 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3187 /// Checks if the elements of this iterator are sorted.
3189 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3190 /// iterator yields exactly zero or one element, `true` is returned.
3192 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3193 /// implies that this function returns `false` if any two consecutive items are not
3199 /// #![feature(is_sorted)]
3201 /// assert!([1, 2, 2, 9].iter().is_sorted());
3202 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3203 /// assert!([0].iter().is_sorted());
3204 /// assert!(std::iter::empty::<i32>().is_sorted());
3205 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3208 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3209 fn is_sorted(self) -> bool
3212 Self::Item: PartialOrd,
3214 self.is_sorted_by(PartialOrd::partial_cmp)
3217 /// Checks if the elements of this iterator are sorted using the given comparator function.
3219 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3220 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3221 /// [`is_sorted`]; see its documentation for more information.
3226 /// #![feature(is_sorted)]
3228 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3229 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3230 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3231 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3232 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3235 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3236 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3237 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3240 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3242 let mut last = match self.next() {
3244 None => return true,
3247 while let Some(curr) = self.next() {
3248 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3257 /// Checks if the elements of this iterator are sorted using the given key extraction
3260 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3261 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3262 /// its documentation for more information.
3264 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3269 /// #![feature(is_sorted)]
3271 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3272 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3275 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3276 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3279 F: FnMut(Self::Item) -> K,
3282 self.map(f).is_sorted()
3286 #[stable(feature = "rust1", since = "1.0.0")]
3287 impl<I: Iterator + ?Sized> Iterator for &mut I {
3288 type Item = I::Item;
3289 fn next(&mut self) -> Option<I::Item> {
3292 fn size_hint(&self) -> (usize, Option<usize>) {
3293 (**self).size_hint()
3295 fn nth(&mut self, n: usize) -> Option<Self::Item> {