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, ControlFlow, Try};
8 use super::super::TrustedRandomAccess;
9 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
10 use super::super::{FlatMap, Flatten};
11 use super::super::{FromIterator, Intersperse, IntersperseWith, 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]: crate::iter
25 /// [impl]: crate::iter#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"
96 #[must_use = "iterators are lazy and do nothing unless consumed"]
98 /// The type of the elements being iterated over.
99 #[stable(feature = "rust1", since = "1.0.0")]
102 /// Advances the iterator and returns the next value.
104 /// Returns [`None`] when iteration is finished. Individual iterator
105 /// implementations may choose to resume iteration, and so calling `next()`
106 /// again may or may not eventually start returning [`Some(Item)`] again at some
109 /// [`Some(Item)`]: 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());
133 #[stable(feature = "rust1", since = "1.0.0")]
134 fn next(&mut self) -> Option<Self::Item>;
136 /// Returns the bounds on the remaining length of the iterator.
138 /// Specifically, `size_hint()` returns a tuple where the first element
139 /// is the lower bound, and the second element is the upper bound.
141 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
142 /// A [`None`] here means that either there is no known upper bound, or the
143 /// upper bound is larger than [`usize`].
145 /// # Implementation notes
147 /// It is not enforced that an iterator implementation yields the declared
148 /// number of elements. A buggy iterator may yield less than the lower bound
149 /// or more than the upper bound of elements.
151 /// `size_hint()` is primarily intended to be used for optimizations such as
152 /// reserving space for the elements of the iterator, but must not be
153 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
154 /// implementation of `size_hint()` should not lead to memory safety
157 /// That said, the implementation should provide a correct estimation,
158 /// because otherwise it would be a violation of the trait's protocol.
160 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
163 /// [`usize`]: type@usize
170 /// let a = [1, 2, 3];
171 /// let iter = a.iter();
173 /// assert_eq!((3, Some(3)), iter.size_hint());
176 /// A more complex example:
179 /// // The even numbers from zero to ten.
180 /// let iter = (0..10).filter(|x| x % 2 == 0);
182 /// // We might iterate from zero to ten times. Knowing that it's five
183 /// // exactly wouldn't be possible without executing filter().
184 /// assert_eq!((0, Some(10)), iter.size_hint());
186 /// // Let's add five more numbers with chain()
187 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
189 /// // now both bounds are increased by five
190 /// assert_eq!((5, Some(15)), iter.size_hint());
193 /// Returning `None` for an upper bound:
196 /// // an infinite iterator has no upper bound
197 /// // and the maximum possible lower bound
200 /// assert_eq!((usize::MAX, None), iter.size_hint());
203 #[stable(feature = "rust1", since = "1.0.0")]
204 fn size_hint(&self) -> (usize, Option<usize>) {
208 /// Consumes the iterator, counting the number of iterations and returning it.
210 /// This method will call [`next`] repeatedly until [`None`] is encountered,
211 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
212 /// called at least once even if the iterator does not have any elements.
214 /// [`next`]: Iterator::next
216 /// # Overflow Behavior
218 /// The method does no guarding against overflows, so counting elements of
219 /// an iterator with more than [`usize::MAX`] elements either produces the
220 /// wrong result or panics. If debug assertions are enabled, a panic is
225 /// This function might panic if the iterator has more than [`usize::MAX`]
228 /// [`usize::MAX`]: crate::usize::MAX
235 /// let a = [1, 2, 3];
236 /// assert_eq!(a.iter().count(), 3);
238 /// let a = [1, 2, 3, 4, 5];
239 /// assert_eq!(a.iter().count(), 5);
242 #[stable(feature = "rust1", since = "1.0.0")]
243 fn count(self) -> usize
248 fn add1<T>(count: usize, _: T) -> usize {
256 /// Consumes the iterator, returning the last element.
258 /// This method will evaluate the iterator until it returns [`None`]. While
259 /// doing so, it keeps track of the current element. After [`None`] is
260 /// returned, `last()` will then return the last element it saw.
267 /// let a = [1, 2, 3];
268 /// assert_eq!(a.iter().last(), Some(&3));
270 /// let a = [1, 2, 3, 4, 5];
271 /// assert_eq!(a.iter().last(), Some(&5));
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn last(self) -> Option<Self::Item>
280 fn some<T>(_: Option<T>, x: T) -> Option<T> {
284 self.fold(None, some)
287 /// Advances the iterator by `n` elements.
289 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
290 /// times until [`None`] is encountered.
292 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
293 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
294 /// of elements the iterator is advanced by before running out of elements (i.e. the
295 /// length of the iterator). Note that `k` is always less than `n`.
297 /// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
299 /// [`next`]: Iterator::next
306 /// #![feature(iter_advance_by)]
308 /// let a = [1, 2, 3, 4];
309 /// let mut iter = a.iter();
311 /// assert_eq!(iter.advance_by(2), Ok(()));
312 /// assert_eq!(iter.next(), Some(&3));
313 /// assert_eq!(iter.advance_by(0), Ok(()));
314 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
317 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
318 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
320 self.next().ok_or(i)?;
325 /// Returns the `n`th element of the iterator.
327 /// Like most indexing operations, the count starts from zero, so `nth(0)`
328 /// returns the first value, `nth(1)` the second, and so on.
330 /// Note that all preceding elements, as well as the returned element, will be
331 /// consumed from the iterator. That means that the preceding elements will be
332 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
333 /// will return different elements.
335 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
343 /// let a = [1, 2, 3];
344 /// assert_eq!(a.iter().nth(1), Some(&2));
347 /// Calling `nth()` multiple times doesn't rewind the iterator:
350 /// let a = [1, 2, 3];
352 /// let mut iter = a.iter();
354 /// assert_eq!(iter.nth(1), Some(&2));
355 /// assert_eq!(iter.nth(1), None);
358 /// Returning `None` if there are less than `n + 1` elements:
361 /// let a = [1, 2, 3];
362 /// assert_eq!(a.iter().nth(10), None);
365 #[stable(feature = "rust1", since = "1.0.0")]
366 fn nth(&mut self, n: usize) -> Option<Self::Item> {
367 self.advance_by(n).ok()?;
371 /// Creates an iterator starting at the same point, but stepping by
372 /// the given amount at each iteration.
374 /// Note 1: The first element of the iterator will always be returned,
375 /// regardless of the step given.
377 /// Note 2: The time at which ignored elements are pulled is not fixed.
378 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
379 /// but is also free to behave like the sequence
380 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
381 /// Which way is used may change for some iterators for performance reasons.
382 /// The second way will advance the iterator earlier and may consume more items.
384 /// `advance_n_and_return_first` is the equivalent of:
386 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
390 /// let next = iter.next();
391 /// if total_step > 1 {
392 /// iter.nth(total_step-2);
400 /// The method will panic if the given step is `0`.
407 /// let a = [0, 1, 2, 3, 4, 5];
408 /// let mut iter = a.iter().step_by(2);
410 /// assert_eq!(iter.next(), Some(&0));
411 /// assert_eq!(iter.next(), Some(&2));
412 /// assert_eq!(iter.next(), Some(&4));
413 /// assert_eq!(iter.next(), None);
416 #[stable(feature = "iterator_step_by", since = "1.28.0")]
417 fn step_by(self, step: usize) -> StepBy<Self>
421 StepBy::new(self, step)
424 /// Takes two iterators and creates a new iterator over both in sequence.
426 /// `chain()` will return a new iterator which will first iterate over
427 /// values from the first iterator and then over values from the second
430 /// In other words, it links two iterators together, in a chain. 🔗
432 /// [`once`] is commonly used to adapt a single value into a chain of
433 /// other kinds of iteration.
440 /// let a1 = [1, 2, 3];
441 /// let a2 = [4, 5, 6];
443 /// let mut iter = a1.iter().chain(a2.iter());
445 /// assert_eq!(iter.next(), Some(&1));
446 /// assert_eq!(iter.next(), Some(&2));
447 /// assert_eq!(iter.next(), Some(&3));
448 /// assert_eq!(iter.next(), Some(&4));
449 /// assert_eq!(iter.next(), Some(&5));
450 /// assert_eq!(iter.next(), Some(&6));
451 /// assert_eq!(iter.next(), None);
454 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
455 /// anything that can be converted into an [`Iterator`], not just an
456 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
457 /// [`IntoIterator`], and so can be passed to `chain()` directly:
460 /// let s1 = &[1, 2, 3];
461 /// let s2 = &[4, 5, 6];
463 /// let mut iter = s1.iter().chain(s2);
465 /// assert_eq!(iter.next(), Some(&1));
466 /// assert_eq!(iter.next(), Some(&2));
467 /// assert_eq!(iter.next(), Some(&3));
468 /// assert_eq!(iter.next(), Some(&4));
469 /// assert_eq!(iter.next(), Some(&5));
470 /// assert_eq!(iter.next(), Some(&6));
471 /// assert_eq!(iter.next(), None);
474 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
478 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
479 /// use std::os::windows::ffi::OsStrExt;
480 /// s.encode_wide().chain(std::iter::once(0)).collect()
484 /// [`once`]: crate::iter::once
485 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
487 #[stable(feature = "rust1", since = "1.0.0")]
488 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
491 U: IntoIterator<Item = Self::Item>,
493 Chain::new(self, other.into_iter())
496 /// 'Zips up' two iterators into a single iterator of pairs.
498 /// `zip()` returns a new iterator that will iterate over two other
499 /// iterators, returning a tuple where the first element comes from the
500 /// first iterator, and the second element comes from the second iterator.
502 /// In other words, it zips two iterators together, into a single one.
504 /// If either iterator returns [`None`], [`next`] from the zipped iterator
505 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
506 /// short-circuit and `next` will not be called on the second iterator.
513 /// let a1 = [1, 2, 3];
514 /// let a2 = [4, 5, 6];
516 /// let mut iter = a1.iter().zip(a2.iter());
518 /// assert_eq!(iter.next(), Some((&1, &4)));
519 /// assert_eq!(iter.next(), Some((&2, &5)));
520 /// assert_eq!(iter.next(), Some((&3, &6)));
521 /// assert_eq!(iter.next(), None);
524 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
525 /// anything that can be converted into an [`Iterator`], not just an
526 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
527 /// [`IntoIterator`], and so can be passed to `zip()` directly:
530 /// let s1 = &[1, 2, 3];
531 /// let s2 = &[4, 5, 6];
533 /// let mut iter = s1.iter().zip(s2);
535 /// assert_eq!(iter.next(), Some((&1, &4)));
536 /// assert_eq!(iter.next(), Some((&2, &5)));
537 /// assert_eq!(iter.next(), Some((&3, &6)));
538 /// assert_eq!(iter.next(), None);
541 /// `zip()` is often used to zip an infinite iterator to a finite one.
542 /// This works because the finite iterator will eventually return [`None`],
543 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
546 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
548 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
550 /// assert_eq!((0, 'f'), enumerate[0]);
551 /// assert_eq!((0, 'f'), zipper[0]);
553 /// assert_eq!((1, 'o'), enumerate[1]);
554 /// assert_eq!((1, 'o'), zipper[1]);
556 /// assert_eq!((2, 'o'), enumerate[2]);
557 /// assert_eq!((2, 'o'), zipper[2]);
560 /// [`enumerate`]: Iterator::enumerate
561 /// [`next`]: Iterator::next
563 #[stable(feature = "rust1", since = "1.0.0")]
564 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
569 Zip::new(self, other.into_iter())
572 /// Places a copy of `separator` between all elements.
574 /// In case the separator does not implement [`Clone`] or needs to be
575 /// computed every time, use [`intersperse_with`].
582 /// #![feature(iter_intersperse)]
584 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
585 /// assert_eq!(hello, "Hello World !");
588 /// [`Clone`]: crate::clone::Clone
589 /// [`intersperse_with`]: Iterator::intersperse_with
591 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
592 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
597 Intersperse::new(self, separator)
600 /// Places an element generated by `separator` between all elements.
607 /// #![feature(iter_intersperse)]
609 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
611 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
612 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
614 /// let result = src.intersperse_with(separator).collect::<String>();
615 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
618 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
619 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
622 G: FnMut() -> Self::Item,
624 IntersperseWith::new(self, separator)
627 /// Takes a closure and creates an iterator which calls that closure on each
630 /// `map()` transforms one iterator into another, by means of its argument:
631 /// something that implements [`FnMut`]. It produces a new iterator which
632 /// calls this closure on each element of the original iterator.
634 /// If you are good at thinking in types, you can think of `map()` like this:
635 /// If you have an iterator that gives you elements of some type `A`, and
636 /// you want an iterator of some other type `B`, you can use `map()`,
637 /// passing a closure that takes an `A` and returns a `B`.
639 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
640 /// lazy, it is best used when you're already working with other iterators.
641 /// If you're doing some sort of looping for a side effect, it's considered
642 /// more idiomatic to use [`for`] than `map()`.
644 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
645 /// [`FnMut`]: crate::ops::FnMut
652 /// let a = [1, 2, 3];
654 /// let mut iter = a.iter().map(|x| 2 * x);
656 /// assert_eq!(iter.next(), Some(2));
657 /// assert_eq!(iter.next(), Some(4));
658 /// assert_eq!(iter.next(), Some(6));
659 /// assert_eq!(iter.next(), None);
662 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
665 /// # #![allow(unused_must_use)]
666 /// // don't do this:
667 /// (0..5).map(|x| println!("{}", x));
669 /// // it won't even execute, as it is lazy. Rust will warn you about this.
671 /// // Instead, use for:
673 /// println!("{}", x);
677 #[stable(feature = "rust1", since = "1.0.0")]
678 fn map<B, F>(self, f: F) -> Map<Self, F>
681 F: FnMut(Self::Item) -> B,
686 /// Calls a closure on each element of an iterator.
688 /// This is equivalent to using a [`for`] loop on the iterator, although
689 /// `break` and `continue` are not possible from a closure. It's generally
690 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
691 /// when processing items at the end of longer iterator chains. In some
692 /// cases `for_each` may also be faster than a loop, because it will use
693 /// internal iteration on adaptors like `Chain`.
695 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
702 /// use std::sync::mpsc::channel;
704 /// let (tx, rx) = channel();
705 /// (0..5).map(|x| x * 2 + 1)
706 /// .for_each(move |x| tx.send(x).unwrap());
708 /// let v: Vec<_> = rx.iter().collect();
709 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
712 /// For such a small example, a `for` loop may be cleaner, but `for_each`
713 /// might be preferable to keep a functional style with longer iterators:
716 /// (0..5).flat_map(|x| x * 100 .. x * 110)
718 /// .filter(|&(i, x)| (i + x) % 3 == 0)
719 /// .for_each(|(i, x)| println!("{}:{}", i, x));
722 #[stable(feature = "iterator_for_each", since = "1.21.0")]
723 fn for_each<F>(self, f: F)
726 F: FnMut(Self::Item),
729 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
730 move |(), item| f(item)
733 self.fold((), call(f));
736 /// Creates an iterator which uses a closure to determine if an element
737 /// should be yielded.
739 /// Given an element the closure must return `true` or `false`. The returned
740 /// iterator will yield only the elements for which the closure returns
748 /// let a = [0i32, 1, 2];
750 /// let mut iter = a.iter().filter(|x| x.is_positive());
752 /// assert_eq!(iter.next(), Some(&1));
753 /// assert_eq!(iter.next(), Some(&2));
754 /// assert_eq!(iter.next(), None);
757 /// Because the closure passed to `filter()` takes a reference, and many
758 /// iterators iterate over references, this leads to a possibly confusing
759 /// situation, where the type of the closure is a double reference:
762 /// let a = [0, 1, 2];
764 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
766 /// assert_eq!(iter.next(), Some(&2));
767 /// assert_eq!(iter.next(), None);
770 /// It's common to instead use destructuring on the argument to strip away
774 /// let a = [0, 1, 2];
776 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
778 /// assert_eq!(iter.next(), Some(&2));
779 /// assert_eq!(iter.next(), None);
785 /// let a = [0, 1, 2];
787 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
789 /// assert_eq!(iter.next(), Some(&2));
790 /// assert_eq!(iter.next(), None);
795 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
797 #[stable(feature = "rust1", since = "1.0.0")]
798 fn filter<P>(self, predicate: P) -> Filter<Self, P>
801 P: FnMut(&Self::Item) -> bool,
803 Filter::new(self, predicate)
806 /// Creates an iterator that both filters and maps.
808 /// The returned iterator yields only the `value`s for which the supplied
809 /// closure returns `Some(value)`.
811 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
812 /// concise. The example below shows how a `map().filter().map()` can be
813 /// shortened to a single call to `filter_map`.
815 /// [`filter`]: Iterator::filter
816 /// [`map`]: Iterator::map
823 /// let a = ["1", "two", "NaN", "four", "5"];
825 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
827 /// assert_eq!(iter.next(), Some(1));
828 /// assert_eq!(iter.next(), Some(5));
829 /// assert_eq!(iter.next(), None);
832 /// Here's the same example, but with [`filter`] and [`map`]:
835 /// let a = ["1", "two", "NaN", "four", "5"];
836 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
837 /// assert_eq!(iter.next(), Some(1));
838 /// assert_eq!(iter.next(), Some(5));
839 /// assert_eq!(iter.next(), None);
842 #[stable(feature = "rust1", since = "1.0.0")]
843 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
846 F: FnMut(Self::Item) -> Option<B>,
848 FilterMap::new(self, f)
851 /// Creates an iterator which gives the current iteration count as well as
854 /// The iterator returned yields pairs `(i, val)`, where `i` is the
855 /// current index of iteration and `val` is the value returned by the
858 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
859 /// different sized integer, the [`zip`] function provides similar
862 /// # Overflow Behavior
864 /// The method does no guarding against overflows, so enumerating more than
865 /// [`usize::MAX`] elements either produces the wrong result or panics. If
866 /// debug assertions are enabled, a panic is guaranteed.
870 /// The returned iterator might panic if the to-be-returned index would
871 /// overflow a [`usize`].
873 /// [`usize`]: type@usize
874 /// [`usize::MAX`]: crate::usize::MAX
875 /// [`zip`]: Iterator::zip
880 /// let a = ['a', 'b', 'c'];
882 /// let mut iter = a.iter().enumerate();
884 /// assert_eq!(iter.next(), Some((0, &'a')));
885 /// assert_eq!(iter.next(), Some((1, &'b')));
886 /// assert_eq!(iter.next(), Some((2, &'c')));
887 /// assert_eq!(iter.next(), None);
890 #[stable(feature = "rust1", since = "1.0.0")]
891 fn enumerate(self) -> Enumerate<Self>
898 /// Creates an iterator which can use [`peek`] to look at the next element of
899 /// the iterator without consuming it.
901 /// Adds a [`peek`] method to an iterator. See its documentation for
902 /// more information.
904 /// Note that the underlying iterator is still advanced when [`peek`] is
905 /// called for the first time: In order to retrieve the next element,
906 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
907 /// anything other than fetching the next value) of the [`next`] method
910 /// [`peek`]: Peekable::peek
911 /// [`next`]: Iterator::next
918 /// let xs = [1, 2, 3];
920 /// let mut iter = xs.iter().peekable();
922 /// // peek() lets us see into the future
923 /// assert_eq!(iter.peek(), Some(&&1));
924 /// assert_eq!(iter.next(), Some(&1));
926 /// assert_eq!(iter.next(), Some(&2));
928 /// // we can peek() multiple times, the iterator won't advance
929 /// assert_eq!(iter.peek(), Some(&&3));
930 /// assert_eq!(iter.peek(), Some(&&3));
932 /// assert_eq!(iter.next(), Some(&3));
934 /// // after the iterator is finished, so is peek()
935 /// assert_eq!(iter.peek(), None);
936 /// assert_eq!(iter.next(), None);
939 #[stable(feature = "rust1", since = "1.0.0")]
940 fn peekable(self) -> Peekable<Self>
947 /// Creates an iterator that [`skip`]s elements based on a predicate.
949 /// [`skip`]: Iterator::skip
951 /// `skip_while()` takes a closure as an argument. It will call this
952 /// closure on each element of the iterator, and ignore elements
953 /// until it returns `false`.
955 /// After `false` is returned, `skip_while()`'s job is over, and the
956 /// rest of the elements are yielded.
963 /// let a = [-1i32, 0, 1];
965 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
967 /// assert_eq!(iter.next(), Some(&0));
968 /// assert_eq!(iter.next(), Some(&1));
969 /// assert_eq!(iter.next(), None);
972 /// Because the closure passed to `skip_while()` takes a reference, and many
973 /// iterators iterate over references, this leads to a possibly confusing
974 /// situation, where the type of the closure is a double reference:
977 /// let a = [-1, 0, 1];
979 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
981 /// assert_eq!(iter.next(), Some(&0));
982 /// assert_eq!(iter.next(), Some(&1));
983 /// assert_eq!(iter.next(), None);
986 /// Stopping after an initial `false`:
989 /// let a = [-1, 0, 1, -2];
991 /// let mut iter = a.iter().skip_while(|x| **x < 0);
993 /// assert_eq!(iter.next(), Some(&0));
994 /// assert_eq!(iter.next(), Some(&1));
996 /// // while this would have been false, since we already got a false,
997 /// // skip_while() isn't used any more
998 /// assert_eq!(iter.next(), Some(&-2));
1000 /// assert_eq!(iter.next(), None);
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1007 P: FnMut(&Self::Item) -> bool,
1009 SkipWhile::new(self, predicate)
1012 /// Creates an iterator that yields elements based on a predicate.
1014 /// `take_while()` takes a closure as an argument. It will call this
1015 /// closure on each element of the iterator, and yield elements
1016 /// while it returns `true`.
1018 /// After `false` is returned, `take_while()`'s job is over, and the
1019 /// rest of the elements are ignored.
1026 /// let a = [-1i32, 0, 1];
1028 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1030 /// assert_eq!(iter.next(), Some(&-1));
1031 /// assert_eq!(iter.next(), None);
1034 /// Because the closure passed to `take_while()` takes a reference, and many
1035 /// iterators iterate over references, this leads to a possibly confusing
1036 /// situation, where the type of the closure is a double reference:
1039 /// let a = [-1, 0, 1];
1041 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1043 /// assert_eq!(iter.next(), Some(&-1));
1044 /// assert_eq!(iter.next(), None);
1047 /// Stopping after an initial `false`:
1050 /// let a = [-1, 0, 1, -2];
1052 /// let mut iter = a.iter().take_while(|x| **x < 0);
1054 /// assert_eq!(iter.next(), Some(&-1));
1056 /// // We have more elements that are less than zero, but since we already
1057 /// // got a false, take_while() isn't used any more
1058 /// assert_eq!(iter.next(), None);
1061 /// Because `take_while()` needs to look at the value in order to see if it
1062 /// should be included or not, consuming iterators will see that it is
1066 /// let a = [1, 2, 3, 4];
1067 /// let mut iter = a.iter();
1069 /// let result: Vec<i32> = iter.by_ref()
1070 /// .take_while(|n| **n != 3)
1074 /// assert_eq!(result, &[1, 2]);
1076 /// let result: Vec<i32> = iter.cloned().collect();
1078 /// assert_eq!(result, &[4]);
1081 /// The `3` is no longer there, because it was consumed in order to see if
1082 /// the iteration should stop, but wasn't placed back into the iterator.
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1088 P: FnMut(&Self::Item) -> bool,
1090 TakeWhile::new(self, predicate)
1093 /// Creates an iterator that both yields elements based on a predicate and maps.
1095 /// `map_while()` takes a closure as an argument. It will call this
1096 /// closure on each element of the iterator, and yield elements
1097 /// while it returns [`Some(_)`][`Some`].
1104 /// #![feature(iter_map_while)]
1105 /// let a = [-1i32, 4, 0, 1];
1107 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1109 /// assert_eq!(iter.next(), Some(-16));
1110 /// assert_eq!(iter.next(), Some(4));
1111 /// assert_eq!(iter.next(), None);
1114 /// Here's the same example, but with [`take_while`] and [`map`]:
1116 /// [`take_while`]: Iterator::take_while
1117 /// [`map`]: Iterator::map
1120 /// let a = [-1i32, 4, 0, 1];
1122 /// let mut iter = a.iter()
1123 /// .map(|x| 16i32.checked_div(*x))
1124 /// .take_while(|x| x.is_some())
1125 /// .map(|x| x.unwrap());
1127 /// assert_eq!(iter.next(), Some(-16));
1128 /// assert_eq!(iter.next(), Some(4));
1129 /// assert_eq!(iter.next(), None);
1132 /// Stopping after an initial [`None`]:
1135 /// #![feature(iter_map_while)]
1136 /// use std::convert::TryFrom;
1138 /// let a = [0, 1, 2, -3, 4, 5, -6];
1140 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1141 /// let vec = iter.collect::<Vec<_>>();
1143 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1144 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1145 /// assert_eq!(vec, vec![0, 1, 2]);
1148 /// Because `map_while()` needs to look at the value in order to see if it
1149 /// should be included or not, consuming iterators will see that it is
1153 /// #![feature(iter_map_while)]
1154 /// use std::convert::TryFrom;
1156 /// let a = [1, 2, -3, 4];
1157 /// let mut iter = a.iter();
1159 /// let result: Vec<u32> = iter.by_ref()
1160 /// .map_while(|n| u32::try_from(*n).ok())
1163 /// assert_eq!(result, &[1, 2]);
1165 /// let result: Vec<i32> = iter.cloned().collect();
1167 /// assert_eq!(result, &[4]);
1170 /// The `-3` is no longer there, because it was consumed in order to see if
1171 /// the iteration should stop, but wasn't placed back into the iterator.
1173 /// Note that unlike [`take_while`] this iterator is **not** fused.
1174 /// It is also not specified what this iterator returns after the first` None` is returned.
1175 /// If you need fused iterator, use [`fuse`].
1177 /// [`fuse`]: Iterator::fuse
1179 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1180 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1183 P: FnMut(Self::Item) -> Option<B>,
1185 MapWhile::new(self, predicate)
1188 /// Creates an iterator that skips the first `n` elements.
1190 /// After they have been consumed, the rest of the elements are yielded.
1191 /// Rather than overriding this method directly, instead override the `nth` method.
1198 /// let a = [1, 2, 3];
1200 /// let mut iter = a.iter().skip(2);
1202 /// assert_eq!(iter.next(), Some(&3));
1203 /// assert_eq!(iter.next(), None);
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 fn skip(self, n: usize) -> Skip<Self>
1214 /// Creates an iterator that yields its first `n` elements.
1221 /// let a = [1, 2, 3];
1223 /// let mut iter = a.iter().take(2);
1225 /// assert_eq!(iter.next(), Some(&1));
1226 /// assert_eq!(iter.next(), Some(&2));
1227 /// assert_eq!(iter.next(), None);
1230 /// `take()` is often used with an infinite iterator, to make it finite:
1233 /// let mut iter = (0..).take(3);
1235 /// assert_eq!(iter.next(), Some(0));
1236 /// assert_eq!(iter.next(), Some(1));
1237 /// assert_eq!(iter.next(), Some(2));
1238 /// assert_eq!(iter.next(), None);
1241 /// If less than `n` elements are available,
1242 /// `take` will limit itself to the size of the underlying iterator:
1245 /// let v = vec![1, 2];
1246 /// let mut iter = v.into_iter().take(5);
1247 /// assert_eq!(iter.next(), Some(1));
1248 /// assert_eq!(iter.next(), Some(2));
1249 /// assert_eq!(iter.next(), None);
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 fn take(self, n: usize) -> Take<Self>
1260 /// An iterator adaptor similar to [`fold`] that holds internal state and
1261 /// produces a new iterator.
1263 /// [`fold`]: Iterator::fold
1265 /// `scan()` takes two arguments: an initial value which seeds the internal
1266 /// state, and a closure with two arguments, the first being a mutable
1267 /// reference to the internal state and the second an iterator element.
1268 /// The closure can assign to the internal state to share state between
1271 /// On iteration, the closure will be applied to each element of the
1272 /// iterator and the return value from the closure, an [`Option`], is
1273 /// yielded by the iterator.
1280 /// let a = [1, 2, 3];
1282 /// let mut iter = a.iter().scan(1, |state, &x| {
1283 /// // each iteration, we'll multiply the state by the element
1284 /// *state = *state * x;
1286 /// // then, we'll yield the negation of the state
1290 /// assert_eq!(iter.next(), Some(-1));
1291 /// assert_eq!(iter.next(), Some(-2));
1292 /// assert_eq!(iter.next(), Some(-6));
1293 /// assert_eq!(iter.next(), None);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1300 F: FnMut(&mut St, Self::Item) -> Option<B>,
1302 Scan::new(self, initial_state, f)
1305 /// Creates an iterator that works like map, but flattens nested structure.
1307 /// The [`map`] adapter is very useful, but only when the closure
1308 /// argument produces values. If it produces an iterator instead, there's
1309 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1312 /// You can think of `flat_map(f)` as the semantic equivalent
1313 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1315 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1316 /// one item for each element, and `flat_map()`'s closure returns an
1317 /// iterator for each element.
1319 /// [`map`]: Iterator::map
1320 /// [`flatten`]: Iterator::flatten
1327 /// let words = ["alpha", "beta", "gamma"];
1329 /// // chars() returns an iterator
1330 /// let merged: String = words.iter()
1331 /// .flat_map(|s| s.chars())
1333 /// assert_eq!(merged, "alphabetagamma");
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1341 F: FnMut(Self::Item) -> U,
1343 FlatMap::new(self, f)
1346 /// Creates an iterator that flattens nested structure.
1348 /// This is useful when you have an iterator of iterators or an iterator of
1349 /// things that can be turned into iterators and you want to remove one
1350 /// level of indirection.
1357 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1358 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1359 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1362 /// Mapping and then flattening:
1365 /// let words = ["alpha", "beta", "gamma"];
1367 /// // chars() returns an iterator
1368 /// let merged: String = words.iter()
1369 /// .map(|s| s.chars())
1372 /// assert_eq!(merged, "alphabetagamma");
1375 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1376 /// in this case since it conveys intent more clearly:
1379 /// let words = ["alpha", "beta", "gamma"];
1381 /// // chars() returns an iterator
1382 /// let merged: String = words.iter()
1383 /// .flat_map(|s| s.chars())
1385 /// assert_eq!(merged, "alphabetagamma");
1388 /// Flattening only removes one level of nesting at a time:
1391 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1393 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1394 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1396 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1397 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1400 /// Here we see that `flatten()` does not perform a "deep" flatten.
1401 /// Instead, only one level of nesting is removed. That is, if you
1402 /// `flatten()` a three-dimensional array, the result will be
1403 /// two-dimensional and not one-dimensional. To get a one-dimensional
1404 /// structure, you have to `flatten()` again.
1406 /// [`flat_map()`]: Iterator::flat_map
1408 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1409 fn flatten(self) -> Flatten<Self>
1412 Self::Item: IntoIterator,
1417 /// Creates an iterator which ends after the first [`None`].
1419 /// After an iterator returns [`None`], future calls may or may not yield
1420 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1421 /// [`None`] is given, it will always return [`None`] forever.
1423 /// [`Some(T)`]: Some
1430 /// // an iterator which alternates between Some and None
1431 /// struct Alternate {
1435 /// impl Iterator for Alternate {
1436 /// type Item = i32;
1438 /// fn next(&mut self) -> Option<i32> {
1439 /// let val = self.state;
1440 /// self.state = self.state + 1;
1442 /// // if it's even, Some(i32), else None
1443 /// if val % 2 == 0 {
1451 /// let mut iter = Alternate { state: 0 };
1453 /// // we can see our iterator going back and forth
1454 /// assert_eq!(iter.next(), Some(0));
1455 /// assert_eq!(iter.next(), None);
1456 /// assert_eq!(iter.next(), Some(2));
1457 /// assert_eq!(iter.next(), None);
1459 /// // however, once we fuse it...
1460 /// let mut iter = iter.fuse();
1462 /// assert_eq!(iter.next(), Some(4));
1463 /// assert_eq!(iter.next(), None);
1465 /// // it will always return `None` after the first time.
1466 /// assert_eq!(iter.next(), None);
1467 /// assert_eq!(iter.next(), None);
1468 /// assert_eq!(iter.next(), None);
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 fn fuse(self) -> Fuse<Self>
1479 /// Does something with each element of an iterator, passing the value on.
1481 /// When using iterators, you'll often chain several of them together.
1482 /// While working on such code, you might want to check out what's
1483 /// happening at various parts in the pipeline. To do that, insert
1484 /// a call to `inspect()`.
1486 /// It's more common for `inspect()` to be used as a debugging tool than to
1487 /// exist in your final code, but applications may find it useful in certain
1488 /// situations when errors need to be logged before being discarded.
1495 /// let a = [1, 4, 2, 3];
1497 /// // this iterator sequence is complex.
1498 /// let sum = a.iter()
1500 /// .filter(|x| x % 2 == 0)
1501 /// .fold(0, |sum, i| sum + i);
1503 /// println!("{}", sum);
1505 /// // let's add some inspect() calls to investigate what's happening
1506 /// let sum = a.iter()
1508 /// .inspect(|x| println!("about to filter: {}", x))
1509 /// .filter(|x| x % 2 == 0)
1510 /// .inspect(|x| println!("made it through filter: {}", x))
1511 /// .fold(0, |sum, i| sum + i);
1513 /// println!("{}", sum);
1516 /// This will print:
1520 /// about to filter: 1
1521 /// about to filter: 4
1522 /// made it through filter: 4
1523 /// about to filter: 2
1524 /// made it through filter: 2
1525 /// about to filter: 3
1529 /// Logging errors before discarding them:
1532 /// let lines = ["1", "2", "a"];
1534 /// let sum: i32 = lines
1536 /// .map(|line| line.parse::<i32>())
1537 /// .inspect(|num| {
1538 /// if let Err(ref e) = *num {
1539 /// println!("Parsing error: {}", e);
1542 /// .filter_map(Result::ok)
1545 /// println!("Sum: {}", sum);
1548 /// This will print:
1551 /// Parsing error: invalid digit found in string
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1559 F: FnMut(&Self::Item),
1561 Inspect::new(self, f)
1564 /// Borrows an iterator, rather than consuming it.
1566 /// This is useful to allow applying iterator adaptors while still
1567 /// retaining ownership of the original iterator.
1574 /// let a = [1, 2, 3];
1576 /// let iter = a.iter();
1578 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1580 /// assert_eq!(sum, 6);
1582 /// // if we try to use iter again, it won't work. The following line
1583 /// // gives "error: use of moved value: `iter`
1584 /// // assert_eq!(iter.next(), None);
1586 /// // let's try that again
1587 /// let a = [1, 2, 3];
1589 /// let mut iter = a.iter();
1591 /// // instead, we add in a .by_ref()
1592 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1594 /// assert_eq!(sum, 3);
1596 /// // now this is just fine:
1597 /// assert_eq!(iter.next(), Some(&3));
1598 /// assert_eq!(iter.next(), None);
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 fn by_ref(&mut self) -> &mut Self
1608 /// Transforms an iterator into a collection.
1610 /// `collect()` can take anything iterable, and turn it into a relevant
1611 /// collection. This is one of the more powerful methods in the standard
1612 /// library, used in a variety of contexts.
1614 /// The most basic pattern in which `collect()` is used is to turn one
1615 /// collection into another. You take a collection, call [`iter`] on it,
1616 /// do a bunch of transformations, and then `collect()` at the end.
1618 /// `collect()` can also create instances of types that are not typical
1619 /// collections. For example, a [`String`] can be built from [`char`]s,
1620 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1621 /// into `Result<Collection<T>, E>`. See the examples below for more.
1623 /// Because `collect()` is so general, it can cause problems with type
1624 /// inference. As such, `collect()` is one of the few times you'll see
1625 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1626 /// helps the inference algorithm understand specifically which collection
1627 /// you're trying to collect into.
1634 /// let a = [1, 2, 3];
1636 /// let doubled: Vec<i32> = a.iter()
1637 /// .map(|&x| x * 2)
1640 /// assert_eq!(vec![2, 4, 6], doubled);
1643 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1644 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1646 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1649 /// use std::collections::VecDeque;
1651 /// let a = [1, 2, 3];
1653 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1655 /// assert_eq!(2, doubled[0]);
1656 /// assert_eq!(4, doubled[1]);
1657 /// assert_eq!(6, doubled[2]);
1660 /// Using the 'turbofish' instead of annotating `doubled`:
1663 /// let a = [1, 2, 3];
1665 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1667 /// assert_eq!(vec![2, 4, 6], doubled);
1670 /// Because `collect()` only cares about what you're collecting into, you can
1671 /// still use a partial type hint, `_`, with the turbofish:
1674 /// let a = [1, 2, 3];
1676 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1678 /// assert_eq!(vec![2, 4, 6], doubled);
1681 /// Using `collect()` to make a [`String`]:
1684 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1686 /// let hello: String = chars.iter()
1687 /// .map(|&x| x as u8)
1688 /// .map(|x| (x + 1) as char)
1691 /// assert_eq!("hello", hello);
1694 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1695 /// see if any of them failed:
1698 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1700 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1702 /// // gives us the first error
1703 /// assert_eq!(Err("nope"), result);
1705 /// let results = [Ok(1), Ok(3)];
1707 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1709 /// // gives us the list of answers
1710 /// assert_eq!(Ok(vec![1, 3]), result);
1713 /// [`iter`]: Iterator::next
1714 /// [`String`]: ../../std/string/struct.String.html
1715 /// [`char`]: type@char
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1719 fn collect<B: FromIterator<Self::Item>>(self) -> B
1723 FromIterator::from_iter(self)
1726 /// Consumes an iterator, creating two collections from it.
1728 /// The predicate passed to `partition()` can return `true`, or `false`.
1729 /// `partition()` returns a pair, all of the elements for which it returned
1730 /// `true`, and all of the elements for which it returned `false`.
1732 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1734 /// [`is_partitioned()`]: Iterator::is_partitioned
1735 /// [`partition_in_place()`]: Iterator::partition_in_place
1742 /// let a = [1, 2, 3];
1744 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1746 /// .partition(|&n| n % 2 == 0);
1748 /// assert_eq!(even, vec![2]);
1749 /// assert_eq!(odd, vec![1, 3]);
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 fn partition<B, F>(self, f: F) -> (B, B)
1755 B: Default + Extend<Self::Item>,
1756 F: FnMut(&Self::Item) -> bool,
1759 fn extend<'a, T, B: Extend<T>>(
1760 mut f: impl FnMut(&T) -> bool + 'a,
1763 ) -> impl FnMut((), T) + 'a {
1768 right.extend_one(x);
1773 let mut left: B = Default::default();
1774 let mut right: B = Default::default();
1776 self.fold((), extend(f, &mut left, &mut right));
1781 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1782 /// such that all those that return `true` precede all those that return `false`.
1783 /// Returns the number of `true` elements found.
1785 /// The relative order of partitioned items is not maintained.
1787 /// See also [`is_partitioned()`] and [`partition()`].
1789 /// [`is_partitioned()`]: Iterator::is_partitioned
1790 /// [`partition()`]: Iterator::partition
1795 /// #![feature(iter_partition_in_place)]
1797 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1799 /// // Partition in-place between evens and odds
1800 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1802 /// assert_eq!(i, 3);
1803 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1804 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1806 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1807 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1809 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1810 P: FnMut(&T) -> bool,
1812 // FIXME: should we worry about the count overflowing? The only way to have more than
1813 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1815 // These closure "factory" functions exist to avoid genericity in `Self`.
1819 predicate: &'a mut impl FnMut(&T) -> bool,
1820 true_count: &'a mut usize,
1821 ) -> impl FnMut(&&mut T) -> bool + 'a {
1823 let p = predicate(&**x);
1824 *true_count += p as usize;
1830 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1831 move |x| predicate(&**x)
1834 // Repeatedly find the first `false` and swap it with the last `true`.
1835 let mut true_count = 0;
1836 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1837 if let Some(tail) = self.rfind(is_true(predicate)) {
1838 crate::mem::swap(head, tail);
1847 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1848 /// such that all those that return `true` precede all those that return `false`.
1850 /// See also [`partition()`] and [`partition_in_place()`].
1852 /// [`partition()`]: Iterator::partition
1853 /// [`partition_in_place()`]: Iterator::partition_in_place
1858 /// #![feature(iter_is_partitioned)]
1860 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1861 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1863 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1864 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1867 P: FnMut(Self::Item) -> bool,
1869 // Either all items test `true`, or the first clause stops at `false`
1870 // and we check that there are no more `true` items after that.
1871 self.all(&mut predicate) || !self.any(predicate)
1874 /// An iterator method that applies a function as long as it returns
1875 /// successfully, producing a single, final value.
1877 /// `try_fold()` takes two arguments: an initial value, and a closure with
1878 /// two arguments: an 'accumulator', and an element. The closure either
1879 /// returns successfully, with the value that the accumulator should have
1880 /// for the next iteration, or it returns failure, with an error value that
1881 /// is propagated back to the caller immediately (short-circuiting).
1883 /// The initial value is the value the accumulator will have on the first
1884 /// call. If applying the closure succeeded against every element of the
1885 /// iterator, `try_fold()` returns the final accumulator as success.
1887 /// Folding is useful whenever you have a collection of something, and want
1888 /// to produce a single value from it.
1890 /// # Note to Implementors
1892 /// Several of the other (forward) methods have default implementations in
1893 /// terms of this one, so try to implement this explicitly if it can
1894 /// do something better than the default `for` loop implementation.
1896 /// In particular, try to have this call `try_fold()` on the internal parts
1897 /// from which this iterator is composed. If multiple calls are needed,
1898 /// the `?` operator may be convenient for chaining the accumulator value
1899 /// along, but beware any invariants that need to be upheld before those
1900 /// early returns. This is a `&mut self` method, so iteration needs to be
1901 /// resumable after hitting an error here.
1908 /// let a = [1, 2, 3];
1910 /// // the checked sum of all of the elements of the array
1911 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1913 /// assert_eq!(sum, Some(6));
1916 /// Short-circuiting:
1919 /// let a = [10, 20, 30, 100, 40, 50];
1920 /// let mut it = a.iter();
1922 /// // This sum overflows when adding the 100 element
1923 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1924 /// assert_eq!(sum, None);
1926 /// // Because it short-circuited, the remaining elements are still
1927 /// // available through the iterator.
1928 /// assert_eq!(it.len(), 2);
1929 /// assert_eq!(it.next(), Some(&40));
1932 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1933 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1936 F: FnMut(B, Self::Item) -> R,
1939 let mut accum = init;
1940 while let Some(x) = self.next() {
1941 accum = f(accum, x)?;
1946 /// An iterator method that applies a fallible function to each item in the
1947 /// iterator, stopping at the first error and returning that error.
1949 /// This can also be thought of as the fallible form of [`for_each()`]
1950 /// or as the stateless version of [`try_fold()`].
1952 /// [`for_each()`]: Iterator::for_each
1953 /// [`try_fold()`]: Iterator::try_fold
1958 /// use std::fs::rename;
1959 /// use std::io::{stdout, Write};
1960 /// use std::path::Path;
1962 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1964 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1965 /// assert!(res.is_ok());
1967 /// let mut it = data.iter().cloned();
1968 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1969 /// assert!(res.is_err());
1970 /// // It short-circuited, so the remaining items are still in the iterator:
1971 /// assert_eq!(it.next(), Some("stale_bread.json"));
1974 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1975 fn try_for_each<F, R>(&mut self, f: F) -> R
1978 F: FnMut(Self::Item) -> R,
1982 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
1986 self.try_fold((), call(f))
1989 /// An iterator method that applies a function, producing a single, final value.
1991 /// `fold()` takes two arguments: an initial value, and a closure with two
1992 /// arguments: an 'accumulator', and an element. The closure returns the value that
1993 /// the accumulator should have for the next iteration.
1995 /// The initial value is the value the accumulator will have on the first
1998 /// After applying this closure to every element of the iterator, `fold()`
1999 /// returns the accumulator.
2001 /// This operation is sometimes called 'reduce' or 'inject'.
2003 /// Folding is useful whenever you have a collection of something, and want
2004 /// to produce a single value from it.
2006 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2007 /// may not terminate for infinite iterators, even on traits for which a
2008 /// result is determinable in finite time.
2010 /// # Note to Implementors
2012 /// Several of the other (forward) methods have default implementations in
2013 /// terms of this one, so try to implement this explicitly if it can
2014 /// do something better than the default `for` loop implementation.
2016 /// In particular, try to have this call `fold()` on the internal parts
2017 /// from which this iterator is composed.
2024 /// let a = [1, 2, 3];
2026 /// // the sum of all of the elements of the array
2027 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2029 /// assert_eq!(sum, 6);
2032 /// Let's walk through each step of the iteration here:
2034 /// | element | acc | x | result |
2035 /// |---------|-----|---|--------|
2037 /// | 1 | 0 | 1 | 1 |
2038 /// | 2 | 1 | 2 | 3 |
2039 /// | 3 | 3 | 3 | 6 |
2041 /// And so, our final result, `6`.
2043 /// It's common for people who haven't used iterators a lot to
2044 /// use a `for` loop with a list of things to build up a result. Those
2045 /// can be turned into `fold()`s:
2047 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2050 /// let numbers = [1, 2, 3, 4, 5];
2052 /// let mut result = 0;
2055 /// for i in &numbers {
2056 /// result = result + i;
2060 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2062 /// // they're the same
2063 /// assert_eq!(result, result2);
2065 #[doc(alias = "reduce")]
2066 #[doc(alias = "inject")]
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2072 F: FnMut(B, Self::Item) -> B,
2074 let mut accum = init;
2075 while let Some(x) = self.next() {
2076 accum = f(accum, x);
2081 /// The same as [`fold()`], but uses the first element in the
2082 /// iterator as the initial value, folding every subsequent element into it.
2083 /// If the iterator is empty, return [`None`]; otherwise, return the result
2086 /// [`fold()`]: Iterator::fold
2090 /// Find the maximum value:
2093 /// #![feature(iterator_fold_self)]
2095 /// fn find_max<I>(iter: I) -> Option<I::Item>
2096 /// where I: Iterator,
2099 /// iter.fold_first(|a, b| {
2100 /// if a >= b { a } else { b }
2103 /// let a = [10, 20, 5, -23, 0];
2104 /// let b: [u32; 0] = [];
2106 /// assert_eq!(find_max(a.iter()), Some(&20));
2107 /// assert_eq!(find_max(b.iter()), None);
2110 #[unstable(feature = "iterator_fold_self", issue = "68125")]
2111 fn fold_first<F>(mut self, f: F) -> Option<Self::Item>
2114 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2116 let first = self.next()?;
2117 Some(self.fold(first, f))
2120 /// Tests if every element of the iterator matches a predicate.
2122 /// `all()` takes a closure that returns `true` or `false`. It applies
2123 /// this closure to each element of the iterator, and if they all return
2124 /// `true`, then so does `all()`. If any of them return `false`, it
2125 /// returns `false`.
2127 /// `all()` is short-circuiting; in other words, it will stop processing
2128 /// as soon as it finds a `false`, given that no matter what else happens,
2129 /// the result will also be `false`.
2131 /// An empty iterator returns `true`.
2138 /// let a = [1, 2, 3];
2140 /// assert!(a.iter().all(|&x| x > 0));
2142 /// assert!(!a.iter().all(|&x| x > 2));
2145 /// Stopping at the first `false`:
2148 /// let a = [1, 2, 3];
2150 /// let mut iter = a.iter();
2152 /// assert!(!iter.all(|&x| x != 2));
2154 /// // we can still use `iter`, as there are more elements.
2155 /// assert_eq!(iter.next(), Some(&3));
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 fn all<F>(&mut self, f: F) -> bool
2162 F: FnMut(Self::Item) -> bool,
2165 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2167 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2170 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2173 /// Tests if any element of the iterator matches a predicate.
2175 /// `any()` takes a closure that returns `true` or `false`. It applies
2176 /// this closure to each element of the iterator, and if any of them return
2177 /// `true`, then so does `any()`. If they all return `false`, it
2178 /// returns `false`.
2180 /// `any()` is short-circuiting; in other words, it will stop processing
2181 /// as soon as it finds a `true`, given that no matter what else happens,
2182 /// the result will also be `true`.
2184 /// An empty iterator returns `false`.
2191 /// let a = [1, 2, 3];
2193 /// assert!(a.iter().any(|&x| x > 0));
2195 /// assert!(!a.iter().any(|&x| x > 5));
2198 /// Stopping at the first `true`:
2201 /// let a = [1, 2, 3];
2203 /// let mut iter = a.iter();
2205 /// assert!(iter.any(|&x| x != 2));
2207 /// // we can still use `iter`, as there are more elements.
2208 /// assert_eq!(iter.next(), Some(&2));
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 fn any<F>(&mut self, f: F) -> bool
2215 F: FnMut(Self::Item) -> bool,
2218 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2220 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2224 self.try_fold((), check(f)) == ControlFlow::BREAK
2227 /// Searches for an element of an iterator that satisfies a predicate.
2229 /// `find()` takes a closure that returns `true` or `false`. It applies
2230 /// this closure to each element of the iterator, and if any of them return
2231 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2232 /// `false`, it returns [`None`].
2234 /// `find()` is short-circuiting; in other words, it will stop processing
2235 /// as soon as the closure returns `true`.
2237 /// Because `find()` takes a reference, and many iterators iterate over
2238 /// references, this leads to a possibly confusing situation where the
2239 /// argument is a double reference. You can see this effect in the
2240 /// examples below, with `&&x`.
2242 /// [`Some(element)`]: Some
2249 /// let a = [1, 2, 3];
2251 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2253 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2256 /// Stopping at the first `true`:
2259 /// let a = [1, 2, 3];
2261 /// let mut iter = a.iter();
2263 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2265 /// // we can still use `iter`, as there are more elements.
2266 /// assert_eq!(iter.next(), Some(&3));
2269 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2271 #[stable(feature = "rust1", since = "1.0.0")]
2272 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2275 P: FnMut(&Self::Item) -> bool,
2278 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2280 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2284 self.try_fold((), check(predicate)).break_value()
2287 /// Applies function to the elements of iterator and returns
2288 /// the first non-none result.
2290 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2295 /// let a = ["lol", "NaN", "2", "5"];
2297 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2299 /// assert_eq!(first_number, Some(2));
2302 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2303 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2306 F: FnMut(Self::Item) -> Option<B>,
2309 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2310 move |(), x| match f(x) {
2311 Some(x) => ControlFlow::Break(x),
2312 None => ControlFlow::CONTINUE,
2316 self.try_fold((), check(f)).break_value()
2319 /// Applies function to the elements of iterator and returns
2320 /// the first true result or the first error.
2325 /// #![feature(try_find)]
2327 /// let a = ["1", "2", "lol", "NaN", "5"];
2329 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2330 /// Ok(s.parse::<i32>()? == search)
2333 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2334 /// assert_eq!(result, Ok(Some(&"2")));
2336 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2337 /// assert!(result.is_err());
2340 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2341 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2344 F: FnMut(&Self::Item) -> R,
2348 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, R::Error>>
2353 move |(), x| match f(&x).into_result() {
2354 Ok(false) => ControlFlow::CONTINUE,
2355 Ok(true) => ControlFlow::Break(Ok(x)),
2356 Err(x) => ControlFlow::Break(Err(x)),
2360 self.try_fold((), check(f)).break_value().transpose()
2363 /// Searches for an element in an iterator, returning its index.
2365 /// `position()` takes a closure that returns `true` or `false`. It applies
2366 /// this closure to each element of the iterator, and if one of them
2367 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2368 /// them return `false`, it returns [`None`].
2370 /// `position()` is short-circuiting; in other words, it will stop
2371 /// processing as soon as it finds a `true`.
2373 /// # Overflow Behavior
2375 /// The method does no guarding against overflows, so if there are more
2376 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2377 /// result or panics. If debug assertions are enabled, a panic is
2382 /// This function might panic if the iterator has more than `usize::MAX`
2383 /// non-matching elements.
2385 /// [`Some(index)`]: Some
2386 /// [`usize::MAX`]: crate::usize::MAX
2393 /// let a = [1, 2, 3];
2395 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2397 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2400 /// Stopping at the first `true`:
2403 /// let a = [1, 2, 3, 4];
2405 /// let mut iter = a.iter();
2407 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2409 /// // we can still use `iter`, as there are more elements.
2410 /// assert_eq!(iter.next(), Some(&3));
2412 /// // The returned index depends on iterator state
2413 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 fn position<P>(&mut self, predicate: P) -> Option<usize>
2421 P: FnMut(Self::Item) -> bool,
2425 mut predicate: impl FnMut(T) -> bool,
2426 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2427 // The addition might panic on overflow
2430 ControlFlow::Break(i)
2432 ControlFlow::Continue(Add::add(i, 1))
2437 self.try_fold(0, check(predicate)).break_value()
2440 /// Searches for an element in an iterator from the right, returning its
2443 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2444 /// this closure to each element of the iterator, starting from the end,
2445 /// and if one of them returns `true`, then `rposition()` returns
2446 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2448 /// `rposition()` is short-circuiting; in other words, it will stop
2449 /// processing as soon as it finds a `true`.
2451 /// [`Some(index)`]: Some
2458 /// let a = [1, 2, 3];
2460 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2462 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2465 /// Stopping at the first `true`:
2468 /// let a = [1, 2, 3];
2470 /// let mut iter = a.iter();
2472 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2474 /// // we can still use `iter`, as there are more elements.
2475 /// assert_eq!(iter.next(), Some(&1));
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2481 P: FnMut(Self::Item) -> bool,
2482 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2484 // No need for an overflow check here, because `ExactSizeIterator`
2485 // implies that the number of elements fits into a `usize`.
2488 mut predicate: impl FnMut(T) -> bool,
2489 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2492 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2497 self.try_rfold(n, check(predicate)).break_value()
2500 /// Returns the maximum element of an iterator.
2502 /// If several elements are equally maximum, the last element is
2503 /// returned. If the iterator is empty, [`None`] is returned.
2510 /// let a = [1, 2, 3];
2511 /// let b: Vec<u32> = Vec::new();
2513 /// assert_eq!(a.iter().max(), Some(&3));
2514 /// assert_eq!(b.iter().max(), None);
2517 #[stable(feature = "rust1", since = "1.0.0")]
2518 fn max(self) -> Option<Self::Item>
2523 self.max_by(Ord::cmp)
2526 /// Returns the minimum element of an iterator.
2528 /// If several elements are equally minimum, the first element is
2529 /// returned. If the iterator is empty, [`None`] is returned.
2536 /// let a = [1, 2, 3];
2537 /// let b: Vec<u32> = Vec::new();
2539 /// assert_eq!(a.iter().min(), Some(&1));
2540 /// assert_eq!(b.iter().min(), None);
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 fn min(self) -> Option<Self::Item>
2549 self.min_by(Ord::cmp)
2552 /// Returns the element that gives the maximum value from the
2553 /// specified function.
2555 /// If several elements are equally maximum, the last element is
2556 /// returned. If the iterator is empty, [`None`] is returned.
2561 /// let a = [-3_i32, 0, 1, 5, -10];
2562 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2565 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2566 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2569 F: FnMut(&Self::Item) -> B,
2572 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2577 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2581 let (_, x) = self.map(key(f)).max_by(compare)?;
2585 /// Returns the element that gives the maximum value with respect to the
2586 /// specified comparison function.
2588 /// If several elements are equally maximum, the last element is
2589 /// returned. If the iterator is empty, [`None`] is returned.
2594 /// let a = [-3_i32, 0, 1, 5, -10];
2595 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2598 #[stable(feature = "iter_max_by", since = "1.15.0")]
2599 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2602 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2605 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2606 move |x, y| cmp::max_by(x, y, &mut compare)
2609 self.fold_first(fold(compare))
2612 /// Returns the element that gives the minimum value from the
2613 /// specified function.
2615 /// If several elements are equally minimum, the first element is
2616 /// returned. If the iterator is empty, [`None`] is returned.
2621 /// let a = [-3_i32, 0, 1, 5, -10];
2622 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2625 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2626 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2629 F: FnMut(&Self::Item) -> B,
2632 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2637 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2641 let (_, x) = self.map(key(f)).min_by(compare)?;
2645 /// Returns the element that gives the minimum value with respect to the
2646 /// specified comparison function.
2648 /// If several elements are equally minimum, the first element is
2649 /// returned. If the iterator is empty, [`None`] is returned.
2654 /// let a = [-3_i32, 0, 1, 5, -10];
2655 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2658 #[stable(feature = "iter_min_by", since = "1.15.0")]
2659 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2662 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2665 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2666 move |x, y| cmp::min_by(x, y, &mut compare)
2669 self.fold_first(fold(compare))
2672 /// Reverses an iterator's direction.
2674 /// Usually, iterators iterate from left to right. After using `rev()`,
2675 /// an iterator will instead iterate from right to left.
2677 /// This is only possible if the iterator has an end, so `rev()` only
2678 /// works on [`DoubleEndedIterator`]s.
2683 /// let a = [1, 2, 3];
2685 /// let mut iter = a.iter().rev();
2687 /// assert_eq!(iter.next(), Some(&3));
2688 /// assert_eq!(iter.next(), Some(&2));
2689 /// assert_eq!(iter.next(), Some(&1));
2691 /// assert_eq!(iter.next(), None);
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 fn rev(self) -> Rev<Self>
2697 Self: Sized + DoubleEndedIterator,
2702 /// Converts an iterator of pairs into a pair of containers.
2704 /// `unzip()` consumes an entire iterator of pairs, producing two
2705 /// collections: one from the left elements of the pairs, and one
2706 /// from the right elements.
2708 /// This function is, in some sense, the opposite of [`zip`].
2710 /// [`zip`]: Iterator::zip
2717 /// let a = [(1, 2), (3, 4)];
2719 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2721 /// assert_eq!(left, [1, 3]);
2722 /// assert_eq!(right, [2, 4]);
2724 #[stable(feature = "rust1", since = "1.0.0")]
2725 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2727 FromA: Default + Extend<A>,
2728 FromB: Default + Extend<B>,
2729 Self: Sized + Iterator<Item = (A, B)>,
2731 fn extend<'a, A, B>(
2732 ts: &'a mut impl Extend<A>,
2733 us: &'a mut impl Extend<B>,
2734 ) -> impl FnMut((), (A, B)) + 'a {
2741 let mut ts: FromA = Default::default();
2742 let mut us: FromB = Default::default();
2744 let (lower_bound, _) = self.size_hint();
2745 if lower_bound > 0 {
2746 ts.extend_reserve(lower_bound);
2747 us.extend_reserve(lower_bound);
2750 self.fold((), extend(&mut ts, &mut us));
2755 /// Creates an iterator which copies all of its elements.
2757 /// This is useful when you have an iterator over `&T`, but you need an
2758 /// iterator over `T`.
2765 /// let a = [1, 2, 3];
2767 /// let v_copied: Vec<_> = a.iter().copied().collect();
2769 /// // copied is the same as .map(|&x| x)
2770 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2772 /// assert_eq!(v_copied, vec![1, 2, 3]);
2773 /// assert_eq!(v_map, vec![1, 2, 3]);
2775 #[stable(feature = "iter_copied", since = "1.36.0")]
2776 fn copied<'a, T: 'a>(self) -> Copied<Self>
2778 Self: Sized + Iterator<Item = &'a T>,
2784 /// Creates an iterator which [`clone`]s all of its elements.
2786 /// This is useful when you have an iterator over `&T`, but you need an
2787 /// iterator over `T`.
2789 /// [`clone`]: Clone::clone
2796 /// let a = [1, 2, 3];
2798 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2800 /// // cloned is the same as .map(|&x| x), for integers
2801 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2803 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2804 /// assert_eq!(v_map, vec![1, 2, 3]);
2806 #[stable(feature = "rust1", since = "1.0.0")]
2807 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2809 Self: Sized + Iterator<Item = &'a T>,
2815 /// Repeats an iterator endlessly.
2817 /// Instead of stopping at [`None`], the iterator will instead start again,
2818 /// from the beginning. After iterating again, it will start at the
2819 /// beginning again. And again. And again. Forever.
2826 /// let a = [1, 2, 3];
2828 /// let mut it = a.iter().cycle();
2830 /// assert_eq!(it.next(), Some(&1));
2831 /// assert_eq!(it.next(), Some(&2));
2832 /// assert_eq!(it.next(), Some(&3));
2833 /// assert_eq!(it.next(), Some(&1));
2834 /// assert_eq!(it.next(), Some(&2));
2835 /// assert_eq!(it.next(), Some(&3));
2836 /// assert_eq!(it.next(), Some(&1));
2838 #[stable(feature = "rust1", since = "1.0.0")]
2840 fn cycle(self) -> Cycle<Self>
2842 Self: Sized + Clone,
2847 /// Sums the elements of an iterator.
2849 /// Takes each element, adds them together, and returns the result.
2851 /// An empty iterator returns the zero value of the type.
2855 /// When calling `sum()` and a primitive integer type is being returned, this
2856 /// method will panic if the computation overflows and debug assertions are
2864 /// let a = [1, 2, 3];
2865 /// let sum: i32 = a.iter().sum();
2867 /// assert_eq!(sum, 6);
2869 #[stable(feature = "iter_arith", since = "1.11.0")]
2870 fn sum<S>(self) -> S
2878 /// Iterates over the entire iterator, multiplying all the elements
2880 /// An empty iterator returns the one value of the type.
2884 /// When calling `product()` and a primitive integer type is being returned,
2885 /// method will panic if the computation overflows and debug assertions are
2891 /// fn factorial(n: u32) -> u32 {
2892 /// (1..=n).product()
2894 /// assert_eq!(factorial(0), 1);
2895 /// assert_eq!(factorial(1), 1);
2896 /// assert_eq!(factorial(5), 120);
2898 #[stable(feature = "iter_arith", since = "1.11.0")]
2899 fn product<P>(self) -> P
2902 P: Product<Self::Item>,
2904 Product::product(self)
2907 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2913 /// use std::cmp::Ordering;
2915 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2916 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2917 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2919 #[stable(feature = "iter_order", since = "1.5.0")]
2920 fn cmp<I>(self, other: I) -> Ordering
2922 I: IntoIterator<Item = Self::Item>,
2926 self.cmp_by(other, |x, y| x.cmp(&y))
2929 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2930 /// of another with respect to the specified comparison function.
2937 /// #![feature(iter_order_by)]
2939 /// use std::cmp::Ordering;
2941 /// let xs = [1, 2, 3, 4];
2942 /// let ys = [1, 4, 9, 16];
2944 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2945 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2946 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2948 #[unstable(feature = "iter_order_by", issue = "64295")]
2949 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
2953 F: FnMut(Self::Item, I::Item) -> Ordering,
2955 let mut other = other.into_iter();
2958 let x = match self.next() {
2960 if other.next().is_none() {
2961 return Ordering::Equal;
2963 return Ordering::Less;
2969 let y = match other.next() {
2970 None => return Ordering::Greater,
2975 Ordering::Equal => (),
2976 non_eq => return non_eq,
2981 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2987 /// use std::cmp::Ordering;
2989 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2990 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2991 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2993 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2995 #[stable(feature = "iter_order", since = "1.5.0")]
2996 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
2999 Self::Item: PartialOrd<I::Item>,
3002 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3005 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3006 /// of another with respect to the specified comparison function.
3013 /// #![feature(iter_order_by)]
3015 /// use std::cmp::Ordering;
3017 /// let xs = [1.0, 2.0, 3.0, 4.0];
3018 /// let ys = [1.0, 4.0, 9.0, 16.0];
3021 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3022 /// Some(Ordering::Less)
3025 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3026 /// Some(Ordering::Equal)
3029 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3030 /// Some(Ordering::Greater)
3033 #[unstable(feature = "iter_order_by", issue = "64295")]
3034 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3038 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3040 let mut other = other.into_iter();
3043 let x = match self.next() {
3045 if other.next().is_none() {
3046 return Some(Ordering::Equal);
3048 return Some(Ordering::Less);
3054 let y = match other.next() {
3055 None => return Some(Ordering::Greater),
3059 match partial_cmp(x, y) {
3060 Some(Ordering::Equal) => (),
3061 non_eq => return non_eq,
3066 /// Determines if the elements of this [`Iterator`] are equal to those of
3072 /// assert_eq!([1].iter().eq([1].iter()), true);
3073 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3075 #[stable(feature = "iter_order", since = "1.5.0")]
3076 fn eq<I>(self, other: I) -> bool
3079 Self::Item: PartialEq<I::Item>,
3082 self.eq_by(other, |x, y| x == y)
3085 /// Determines if the elements of this [`Iterator`] are equal to those of
3086 /// another with respect to the specified equality function.
3093 /// #![feature(iter_order_by)]
3095 /// let xs = [1, 2, 3, 4];
3096 /// let ys = [1, 4, 9, 16];
3098 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3100 #[unstable(feature = "iter_order_by", issue = "64295")]
3101 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3105 F: FnMut(Self::Item, I::Item) -> bool,
3107 let mut other = other.into_iter();
3110 let x = match self.next() {
3111 None => return other.next().is_none(),
3115 let y = match other.next() {
3116 None => return false,
3126 /// Determines if the elements of this [`Iterator`] are unequal to those of
3132 /// assert_eq!([1].iter().ne([1].iter()), false);
3133 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3135 #[stable(feature = "iter_order", since = "1.5.0")]
3136 fn ne<I>(self, other: I) -> bool
3139 Self::Item: PartialEq<I::Item>,
3145 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3146 /// less than those of another.
3151 /// assert_eq!([1].iter().lt([1].iter()), false);
3152 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3153 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3154 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3156 #[stable(feature = "iter_order", since = "1.5.0")]
3157 fn lt<I>(self, other: I) -> bool
3160 Self::Item: PartialOrd<I::Item>,
3163 self.partial_cmp(other) == Some(Ordering::Less)
3166 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3167 /// less or equal to those of another.
3172 /// assert_eq!([1].iter().le([1].iter()), true);
3173 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3174 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3175 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3177 #[stable(feature = "iter_order", since = "1.5.0")]
3178 fn le<I>(self, other: I) -> bool
3181 Self::Item: PartialOrd<I::Item>,
3184 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3187 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3188 /// greater than those of another.
3193 /// assert_eq!([1].iter().gt([1].iter()), false);
3194 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3195 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3196 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3198 #[stable(feature = "iter_order", since = "1.5.0")]
3199 fn gt<I>(self, other: I) -> bool
3202 Self::Item: PartialOrd<I::Item>,
3205 self.partial_cmp(other) == Some(Ordering::Greater)
3208 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3209 /// greater than or equal to those of another.
3214 /// assert_eq!([1].iter().ge([1].iter()), true);
3215 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3216 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3217 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3219 #[stable(feature = "iter_order", since = "1.5.0")]
3220 fn ge<I>(self, other: I) -> bool
3223 Self::Item: PartialOrd<I::Item>,
3226 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3229 /// Checks if the elements of this iterator are sorted.
3231 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3232 /// iterator yields exactly zero or one element, `true` is returned.
3234 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3235 /// implies that this function returns `false` if any two consecutive items are not
3241 /// #![feature(is_sorted)]
3243 /// assert!([1, 2, 2, 9].iter().is_sorted());
3244 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3245 /// assert!([0].iter().is_sorted());
3246 /// assert!(std::iter::empty::<i32>().is_sorted());
3247 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3250 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3251 fn is_sorted(self) -> bool
3254 Self::Item: PartialOrd,
3256 self.is_sorted_by(PartialOrd::partial_cmp)
3259 /// Checks if the elements of this iterator are sorted using the given comparator function.
3261 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3262 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3263 /// [`is_sorted`]; see its documentation for more information.
3268 /// #![feature(is_sorted)]
3270 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3271 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3272 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3273 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3274 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3277 /// [`is_sorted`]: Iterator::is_sorted
3278 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3279 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3282 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3284 let mut last = match self.next() {
3286 None => return true,
3289 while let Some(curr) = self.next() {
3290 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3299 /// Checks if the elements of this iterator are sorted using the given key extraction
3302 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3303 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3304 /// its documentation for more information.
3306 /// [`is_sorted`]: Iterator::is_sorted
3311 /// #![feature(is_sorted)]
3313 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3314 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3317 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3318 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3321 F: FnMut(Self::Item) -> K,
3324 self.map(f).is_sorted()
3327 /// See [TrustedRandomAccess]
3328 // The unusual name is to avoid name collisions in method resolution
3332 #[unstable(feature = "trusted_random_access", issue = "none")]
3333 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3335 Self: TrustedRandomAccess,
3337 unreachable!("Always specialized");
3341 #[stable(feature = "rust1", since = "1.0.0")]
3342 impl<I: Iterator + ?Sized> Iterator for &mut I {
3343 type Item = I::Item;
3344 fn next(&mut self) -> Option<I::Item> {
3347 fn size_hint(&self) -> (usize, Option<usize>) {
3348 (**self).size_hint()
3350 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3351 (**self).advance_by(n)
3353 fn nth(&mut self, n: usize) -> Option<Self::Item> {