1 use crate::cmp::{self, Ordering};
2 use crate::ops::{ControlFlow, Try};
4 use super::super::TrustedRandomAccessNoCoerce;
5 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
6 use super::super::{FlatMap, Flatten};
7 use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip};
9 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
12 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
14 /// An interface for dealing with iterators.
16 /// This is the main iterator trait. For more about the concept of iterators
17 /// generally, please see the [module-level documentation]. In particular, you
18 /// may want to know how to [implement `Iterator`][impl].
20 /// [module-level documentation]: crate::iter
21 /// [impl]: crate::iter#implementing-iterator
22 #[stable(feature = "rust1", since = "1.0.0")]
23 #[rustc_on_unimplemented(
25 _Self = "std::ops::RangeTo<Idx>",
26 label = "if you meant to iterate until a value, add a starting value",
27 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
28 bounded `Range`: `0..end`"
31 _Self = "std::ops::RangeToInclusive<Idx>",
32 label = "if you meant to iterate until a value (including it), add a starting value",
33 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
34 to have a bounded `RangeInclusive`: `0..=end`"
38 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
41 _Self = "std::string::String",
42 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
46 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
47 syntax `start..end` or the inclusive range syntax `start..=end`"
49 label = "`{Self}` is not an iterator",
50 message = "`{Self}` is not an iterator"
53 #[rustc_diagnostic_item = "Iterator"]
54 #[must_use = "iterators are lazy and do nothing unless consumed"]
56 /// The type of the elements being iterated over.
57 #[stable(feature = "rust1", since = "1.0.0")]
60 /// Advances the iterator and returns the next value.
62 /// Returns [`None`] when iteration is finished. Individual iterator
63 /// implementations may choose to resume iteration, and so calling `next()`
64 /// again may or may not eventually start returning [`Some(Item)`] again at some
67 /// [`Some(Item)`]: Some
74 /// let a = [1, 2, 3];
76 /// let mut iter = a.iter();
78 /// // A call to next() returns the next value...
79 /// assert_eq!(Some(&1), iter.next());
80 /// assert_eq!(Some(&2), iter.next());
81 /// assert_eq!(Some(&3), iter.next());
83 /// // ... and then None once it's over.
84 /// assert_eq!(None, iter.next());
86 /// // More calls may or may not return `None`. Here, they always will.
87 /// assert_eq!(None, iter.next());
88 /// assert_eq!(None, iter.next());
91 #[stable(feature = "rust1", since = "1.0.0")]
92 fn next(&mut self) -> Option<Self::Item>;
94 /// Returns the bounds on the remaining length of the iterator.
96 /// Specifically, `size_hint()` returns a tuple where the first element
97 /// is the lower bound, and the second element is the upper bound.
99 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
100 /// A [`None`] here means that either there is no known upper bound, or the
101 /// upper bound is larger than [`usize`].
103 /// # Implementation notes
105 /// It is not enforced that an iterator implementation yields the declared
106 /// number of elements. A buggy iterator may yield less than the lower bound
107 /// or more than the upper bound of elements.
109 /// `size_hint()` is primarily intended to be used for optimizations such as
110 /// reserving space for the elements of the iterator, but must not be
111 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
112 /// implementation of `size_hint()` should not lead to memory safety
115 /// That said, the implementation should provide a correct estimation,
116 /// because otherwise it would be a violation of the trait's protocol.
118 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
121 /// [`usize`]: type@usize
128 /// let a = [1, 2, 3];
129 /// let iter = a.iter();
131 /// assert_eq!((3, Some(3)), iter.size_hint());
134 /// A more complex example:
137 /// // The even numbers in the range of zero to nine.
138 /// let iter = (0..10).filter(|x| x % 2 == 0);
140 /// // We might iterate from zero to ten times. Knowing that it's five
141 /// // exactly wouldn't be possible without executing filter().
142 /// assert_eq!((0, Some(10)), iter.size_hint());
144 /// // Let's add five more numbers with chain()
145 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
147 /// // now both bounds are increased by five
148 /// assert_eq!((5, Some(15)), iter.size_hint());
151 /// Returning `None` for an upper bound:
154 /// // an infinite iterator has no upper bound
155 /// // and the maximum possible lower bound
158 /// assert_eq!((usize::MAX, None), iter.size_hint());
161 #[stable(feature = "rust1", since = "1.0.0")]
162 fn size_hint(&self) -> (usize, Option<usize>) {
166 /// Consumes the iterator, counting the number of iterations and returning it.
168 /// This method will call [`next`] repeatedly until [`None`] is encountered,
169 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
170 /// called at least once even if the iterator does not have any elements.
172 /// [`next`]: Iterator::next
174 /// # Overflow Behavior
176 /// The method does no guarding against overflows, so counting elements of
177 /// an iterator with more than [`usize::MAX`] elements either produces the
178 /// wrong result or panics. If debug assertions are enabled, a panic is
183 /// This function might panic if the iterator has more than [`usize::MAX`]
191 /// let a = [1, 2, 3];
192 /// assert_eq!(a.iter().count(), 3);
194 /// let a = [1, 2, 3, 4, 5];
195 /// assert_eq!(a.iter().count(), 5);
198 #[stable(feature = "rust1", since = "1.0.0")]
199 fn count(self) -> usize
205 #[rustc_inherit_overflow_checks]
206 |count, _| count + 1,
210 /// Consumes the iterator, returning the last element.
212 /// This method will evaluate the iterator until it returns [`None`]. While
213 /// doing so, it keeps track of the current element. After [`None`] is
214 /// returned, `last()` will then return the last element it saw.
221 /// let a = [1, 2, 3];
222 /// assert_eq!(a.iter().last(), Some(&3));
224 /// let a = [1, 2, 3, 4, 5];
225 /// assert_eq!(a.iter().last(), Some(&5));
228 #[stable(feature = "rust1", since = "1.0.0")]
229 fn last(self) -> Option<Self::Item>
234 fn some<T>(_: Option<T>, x: T) -> Option<T> {
238 self.fold(None, some)
241 /// Advances the iterator by `n` elements.
243 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
244 /// times until [`None`] is encountered.
246 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
247 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
248 /// of elements the iterator is advanced by before running out of elements (i.e. the
249 /// length of the iterator). Note that `k` is always less than `n`.
251 /// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
253 /// [`next`]: Iterator::next
260 /// #![feature(iter_advance_by)]
262 /// let a = [1, 2, 3, 4];
263 /// let mut iter = a.iter();
265 /// assert_eq!(iter.advance_by(2), Ok(()));
266 /// assert_eq!(iter.next(), Some(&3));
267 /// assert_eq!(iter.advance_by(0), Ok(()));
268 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
271 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
272 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
274 self.next().ok_or(i)?;
279 /// Returns the `n`th element of the iterator.
281 /// Like most indexing operations, the count starts from zero, so `nth(0)`
282 /// returns the first value, `nth(1)` the second, and so on.
284 /// Note that all preceding elements, as well as the returned element, will be
285 /// consumed from the iterator. That means that the preceding elements will be
286 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
287 /// will return different elements.
289 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
297 /// let a = [1, 2, 3];
298 /// assert_eq!(a.iter().nth(1), Some(&2));
301 /// Calling `nth()` multiple times doesn't rewind the iterator:
304 /// let a = [1, 2, 3];
306 /// let mut iter = a.iter();
308 /// assert_eq!(iter.nth(1), Some(&2));
309 /// assert_eq!(iter.nth(1), None);
312 /// Returning `None` if there are less than `n + 1` elements:
315 /// let a = [1, 2, 3];
316 /// assert_eq!(a.iter().nth(10), None);
319 #[stable(feature = "rust1", since = "1.0.0")]
320 fn nth(&mut self, n: usize) -> Option<Self::Item> {
321 self.advance_by(n).ok()?;
325 /// Creates an iterator starting at the same point, but stepping by
326 /// the given amount at each iteration.
328 /// Note 1: The first element of the iterator will always be returned,
329 /// regardless of the step given.
331 /// Note 2: The time at which ignored elements are pulled is not fixed.
332 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
333 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
334 /// `advance_n_and_return_first(&mut self, step)`,
335 /// `advance_n_and_return_first(&mut self, step)`, …
336 /// Which way is used may change for some iterators for performance reasons.
337 /// The second way will advance the iterator earlier and may consume more items.
339 /// `advance_n_and_return_first` is the equivalent of:
341 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
345 /// let next = iter.next();
355 /// The method will panic if the given step is `0`.
362 /// let a = [0, 1, 2, 3, 4, 5];
363 /// let mut iter = a.iter().step_by(2);
365 /// assert_eq!(iter.next(), Some(&0));
366 /// assert_eq!(iter.next(), Some(&2));
367 /// assert_eq!(iter.next(), Some(&4));
368 /// assert_eq!(iter.next(), None);
371 #[stable(feature = "iterator_step_by", since = "1.28.0")]
372 fn step_by(self, step: usize) -> StepBy<Self>
376 StepBy::new(self, step)
379 /// Takes two iterators and creates a new iterator over both in sequence.
381 /// `chain()` will return a new iterator which will first iterate over
382 /// values from the first iterator and then over values from the second
385 /// In other words, it links two iterators together, in a chain. 🔗
387 /// [`once`] is commonly used to adapt a single value into a chain of
388 /// other kinds of iteration.
395 /// let a1 = [1, 2, 3];
396 /// let a2 = [4, 5, 6];
398 /// let mut iter = a1.iter().chain(a2.iter());
400 /// assert_eq!(iter.next(), Some(&1));
401 /// assert_eq!(iter.next(), Some(&2));
402 /// assert_eq!(iter.next(), Some(&3));
403 /// assert_eq!(iter.next(), Some(&4));
404 /// assert_eq!(iter.next(), Some(&5));
405 /// assert_eq!(iter.next(), Some(&6));
406 /// assert_eq!(iter.next(), None);
409 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
410 /// anything that can be converted into an [`Iterator`], not just an
411 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
412 /// [`IntoIterator`], and so can be passed to `chain()` directly:
415 /// let s1 = &[1, 2, 3];
416 /// let s2 = &[4, 5, 6];
418 /// let mut iter = s1.iter().chain(s2);
420 /// assert_eq!(iter.next(), Some(&1));
421 /// assert_eq!(iter.next(), Some(&2));
422 /// assert_eq!(iter.next(), Some(&3));
423 /// assert_eq!(iter.next(), Some(&4));
424 /// assert_eq!(iter.next(), Some(&5));
425 /// assert_eq!(iter.next(), Some(&6));
426 /// assert_eq!(iter.next(), None);
429 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
433 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
434 /// use std::os::windows::ffi::OsStrExt;
435 /// s.encode_wide().chain(std::iter::once(0)).collect()
439 /// [`once`]: crate::iter::once
440 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
442 #[stable(feature = "rust1", since = "1.0.0")]
443 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
446 U: IntoIterator<Item = Self::Item>,
448 Chain::new(self, other.into_iter())
451 /// 'Zips up' two iterators into a single iterator of pairs.
453 /// `zip()` returns a new iterator that will iterate over two other
454 /// iterators, returning a tuple where the first element comes from the
455 /// first iterator, and the second element comes from the second iterator.
457 /// In other words, it zips two iterators together, into a single one.
459 /// If either iterator returns [`None`], [`next`] from the zipped iterator
460 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
461 /// short-circuit and `next` will not be called on the second iterator.
468 /// let a1 = [1, 2, 3];
469 /// let a2 = [4, 5, 6];
471 /// let mut iter = a1.iter().zip(a2.iter());
473 /// assert_eq!(iter.next(), Some((&1, &4)));
474 /// assert_eq!(iter.next(), Some((&2, &5)));
475 /// assert_eq!(iter.next(), Some((&3, &6)));
476 /// assert_eq!(iter.next(), None);
479 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
480 /// anything that can be converted into an [`Iterator`], not just an
481 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
482 /// [`IntoIterator`], and so can be passed to `zip()` directly:
485 /// let s1 = &[1, 2, 3];
486 /// let s2 = &[4, 5, 6];
488 /// let mut iter = s1.iter().zip(s2);
490 /// assert_eq!(iter.next(), Some((&1, &4)));
491 /// assert_eq!(iter.next(), Some((&2, &5)));
492 /// assert_eq!(iter.next(), Some((&3, &6)));
493 /// assert_eq!(iter.next(), None);
496 /// `zip()` is often used to zip an infinite iterator to a finite one.
497 /// This works because the finite iterator will eventually return [`None`],
498 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
501 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
503 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
505 /// assert_eq!((0, 'f'), enumerate[0]);
506 /// assert_eq!((0, 'f'), zipper[0]);
508 /// assert_eq!((1, 'o'), enumerate[1]);
509 /// assert_eq!((1, 'o'), zipper[1]);
511 /// assert_eq!((2, 'o'), enumerate[2]);
512 /// assert_eq!((2, 'o'), zipper[2]);
515 /// [`enumerate`]: Iterator::enumerate
516 /// [`next`]: Iterator::next
518 #[stable(feature = "rust1", since = "1.0.0")]
519 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
524 Zip::new(self, other.into_iter())
527 /// Creates a new iterator which places a copy of `separator` between adjacent
528 /// items of the original iterator.
530 /// In case `separator` does not implement [`Clone`] or needs to be
531 /// computed every time, use [`intersperse_with`].
538 /// #![feature(iter_intersperse)]
540 /// let mut a = [0, 1, 2].iter().intersperse(&100);
541 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
542 /// assert_eq!(a.next(), Some(&100)); // The separator.
543 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
544 /// assert_eq!(a.next(), Some(&100)); // The separator.
545 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
546 /// assert_eq!(a.next(), None); // The iterator is finished.
549 /// `intersperse` can be very useful to join an iterator's items using a common element:
551 /// #![feature(iter_intersperse)]
553 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
554 /// assert_eq!(hello, "Hello World !");
557 /// [`Clone`]: crate::clone::Clone
558 /// [`intersperse_with`]: Iterator::intersperse_with
560 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
561 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
566 Intersperse::new(self, separator)
569 /// Creates a new iterator which places an item generated by `separator`
570 /// between adjacent items of the original iterator.
572 /// The closure will be called exactly once each time an item is placed
573 /// between two adjacent items from the underlying iterator; specifically,
574 /// the closure is not called if the underlying iterator yields less than
575 /// two items and after the last item is yielded.
577 /// If the iterator's item implements [`Clone`], it may be easier to use
585 /// #![feature(iter_intersperse)]
587 /// #[derive(PartialEq, Debug)]
588 /// struct NotClone(usize);
590 /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
591 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
593 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
594 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
595 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
596 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
597 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
598 /// assert_eq!(it.next(), None); // The iterator is finished.
601 /// `intersperse_with` can be used in situations where the separator needs
604 /// #![feature(iter_intersperse)]
606 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
608 /// // The closure mutably borrows its context to generate an item.
609 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
610 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
612 /// let result = src.intersperse_with(separator).collect::<String>();
613 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
615 /// [`Clone`]: crate::clone::Clone
616 /// [`intersperse`]: Iterator::intersperse
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 adapters 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 /// [`zip`]: Iterator::zip
879 /// let a = ['a', 'b', 'c'];
881 /// let mut iter = a.iter().enumerate();
883 /// assert_eq!(iter.next(), Some((0, &'a')));
884 /// assert_eq!(iter.next(), Some((1, &'b')));
885 /// assert_eq!(iter.next(), Some((2, &'c')));
886 /// assert_eq!(iter.next(), None);
889 #[stable(feature = "rust1", since = "1.0.0")]
890 fn enumerate(self) -> Enumerate<Self>
897 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
898 /// to look at the next element of the iterator without consuming it. See
899 /// their documentation for more information.
901 /// Note that the underlying iterator is still advanced when [`peek`] or
902 /// [`peek_mut`] are called for the first time: In order to retrieve the
903 /// next element, [`next`] is called on the underlying iterator, hence any
904 /// side effects (i.e. anything other than fetching the next value) of
905 /// the [`next`] method will occur.
913 /// let xs = [1, 2, 3];
915 /// let mut iter = xs.iter().peekable();
917 /// // peek() lets us see into the future
918 /// assert_eq!(iter.peek(), Some(&&1));
919 /// assert_eq!(iter.next(), Some(&1));
921 /// assert_eq!(iter.next(), Some(&2));
923 /// // we can peek() multiple times, the iterator won't advance
924 /// assert_eq!(iter.peek(), Some(&&3));
925 /// assert_eq!(iter.peek(), Some(&&3));
927 /// assert_eq!(iter.next(), Some(&3));
929 /// // after the iterator is finished, so is peek()
930 /// assert_eq!(iter.peek(), None);
931 /// assert_eq!(iter.next(), None);
934 /// Using [`peek_mut`] to mutate the next item without advancing the
938 /// let xs = [1, 2, 3];
940 /// let mut iter = xs.iter().peekable();
942 /// // `peek_mut()` lets us see into the future
943 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
944 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
945 /// assert_eq!(iter.next(), Some(&1));
947 /// if let Some(mut p) = iter.peek_mut() {
948 /// assert_eq!(*p, &2);
949 /// // put a value into the iterator
953 /// // The value reappears as the iterator continues
954 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
956 /// [`peek`]: Peekable::peek
957 /// [`peek_mut`]: Peekable::peek_mut
958 /// [`next`]: Iterator::next
960 #[stable(feature = "rust1", since = "1.0.0")]
961 fn peekable(self) -> Peekable<Self>
968 /// Creates an iterator that [`skip`]s elements based on a predicate.
970 /// [`skip`]: Iterator::skip
972 /// `skip_while()` takes a closure as an argument. It will call this
973 /// closure on each element of the iterator, and ignore elements
974 /// until it returns `false`.
976 /// After `false` is returned, `skip_while()`'s job is over, and the
977 /// rest of the elements are yielded.
984 /// let a = [-1i32, 0, 1];
986 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
988 /// assert_eq!(iter.next(), Some(&0));
989 /// assert_eq!(iter.next(), Some(&1));
990 /// assert_eq!(iter.next(), None);
993 /// Because the closure passed to `skip_while()` takes a reference, and many
994 /// iterators iterate over references, this leads to a possibly confusing
995 /// situation, where the type of the closure argument is a double reference:
998 /// let a = [-1, 0, 1];
1000 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1002 /// assert_eq!(iter.next(), Some(&0));
1003 /// assert_eq!(iter.next(), Some(&1));
1004 /// assert_eq!(iter.next(), None);
1007 /// Stopping after an initial `false`:
1010 /// let a = [-1, 0, 1, -2];
1012 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1014 /// assert_eq!(iter.next(), Some(&0));
1015 /// assert_eq!(iter.next(), Some(&1));
1017 /// // while this would have been false, since we already got a false,
1018 /// // skip_while() isn't used any more
1019 /// assert_eq!(iter.next(), Some(&-2));
1021 /// assert_eq!(iter.next(), None);
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1028 P: FnMut(&Self::Item) -> bool,
1030 SkipWhile::new(self, predicate)
1033 /// Creates an iterator that yields elements based on a predicate.
1035 /// `take_while()` takes a closure as an argument. It will call this
1036 /// closure on each element of the iterator, and yield elements
1037 /// while it returns `true`.
1039 /// After `false` is returned, `take_while()`'s job is over, and the
1040 /// rest of the elements are ignored.
1047 /// let a = [-1i32, 0, 1];
1049 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1051 /// assert_eq!(iter.next(), Some(&-1));
1052 /// assert_eq!(iter.next(), None);
1055 /// Because the closure passed to `take_while()` takes a reference, and many
1056 /// iterators iterate over references, this leads to a possibly confusing
1057 /// situation, where the type of the closure is a double reference:
1060 /// let a = [-1, 0, 1];
1062 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1064 /// assert_eq!(iter.next(), Some(&-1));
1065 /// assert_eq!(iter.next(), None);
1068 /// Stopping after an initial `false`:
1071 /// let a = [-1, 0, 1, -2];
1073 /// let mut iter = a.iter().take_while(|x| **x < 0);
1075 /// assert_eq!(iter.next(), Some(&-1));
1077 /// // We have more elements that are less than zero, but since we already
1078 /// // got a false, take_while() isn't used any more
1079 /// assert_eq!(iter.next(), None);
1082 /// Because `take_while()` needs to look at the value in order to see if it
1083 /// should be included or not, consuming iterators will see that it is
1087 /// let a = [1, 2, 3, 4];
1088 /// let mut iter = a.iter();
1090 /// let result: Vec<i32> = iter.by_ref()
1091 /// .take_while(|n| **n != 3)
1095 /// assert_eq!(result, &[1, 2]);
1097 /// let result: Vec<i32> = iter.cloned().collect();
1099 /// assert_eq!(result, &[4]);
1102 /// The `3` is no longer there, because it was consumed in order to see if
1103 /// the iteration should stop, but wasn't placed back into the iterator.
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1109 P: FnMut(&Self::Item) -> bool,
1111 TakeWhile::new(self, predicate)
1114 /// Creates an iterator that both yields elements based on a predicate and maps.
1116 /// `map_while()` takes a closure as an argument. It will call this
1117 /// closure on each element of the iterator, and yield elements
1118 /// while it returns [`Some(_)`][`Some`].
1125 /// #![feature(iter_map_while)]
1126 /// let a = [-1i32, 4, 0, 1];
1128 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1130 /// assert_eq!(iter.next(), Some(-16));
1131 /// assert_eq!(iter.next(), Some(4));
1132 /// assert_eq!(iter.next(), None);
1135 /// Here's the same example, but with [`take_while`] and [`map`]:
1137 /// [`take_while`]: Iterator::take_while
1138 /// [`map`]: Iterator::map
1141 /// let a = [-1i32, 4, 0, 1];
1143 /// let mut iter = a.iter()
1144 /// .map(|x| 16i32.checked_div(*x))
1145 /// .take_while(|x| x.is_some())
1146 /// .map(|x| x.unwrap());
1148 /// assert_eq!(iter.next(), Some(-16));
1149 /// assert_eq!(iter.next(), Some(4));
1150 /// assert_eq!(iter.next(), None);
1153 /// Stopping after an initial [`None`]:
1156 /// #![feature(iter_map_while)]
1157 /// use std::convert::TryFrom;
1159 /// let a = [0, 1, 2, -3, 4, 5, -6];
1161 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1162 /// let vec = iter.collect::<Vec<_>>();
1164 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1165 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1166 /// assert_eq!(vec, vec![0, 1, 2]);
1169 /// Because `map_while()` needs to look at the value in order to see if it
1170 /// should be included or not, consuming iterators will see that it is
1174 /// #![feature(iter_map_while)]
1175 /// use std::convert::TryFrom;
1177 /// let a = [1, 2, -3, 4];
1178 /// let mut iter = a.iter();
1180 /// let result: Vec<u32> = iter.by_ref()
1181 /// .map_while(|n| u32::try_from(*n).ok())
1184 /// assert_eq!(result, &[1, 2]);
1186 /// let result: Vec<i32> = iter.cloned().collect();
1188 /// assert_eq!(result, &[4]);
1191 /// The `-3` is no longer there, because it was consumed in order to see if
1192 /// the iteration should stop, but wasn't placed back into the iterator.
1194 /// Note that unlike [`take_while`] this iterator is **not** fused.
1195 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1196 /// If you need fused iterator, use [`fuse`].
1198 /// [`fuse`]: Iterator::fuse
1200 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1201 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1204 P: FnMut(Self::Item) -> Option<B>,
1206 MapWhile::new(self, predicate)
1209 /// Creates an iterator that skips the first `n` elements.
1211 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1212 /// iterator is reached (whichever happens first). After that, all the remaining
1213 /// elements are yielded. In particular, if the original iterator is too short,
1214 /// then the returned iterator is empty.
1216 /// Rather than overriding this method directly, instead override the `nth` method.
1223 /// let a = [1, 2, 3];
1225 /// let mut iter = a.iter().skip(2);
1227 /// assert_eq!(iter.next(), Some(&3));
1228 /// assert_eq!(iter.next(), None);
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 fn skip(self, n: usize) -> Skip<Self>
1239 /// Creates an iterator that yields the first `n` elements, or fewer
1240 /// if the underlying iterator ends sooner.
1242 /// `take(n)` yields elements until `n` elements are yielded or the end of
1243 /// the iterator is reached (whichever happens first).
1244 /// The returned iterator is a prefix of length `n` if the original iterator
1245 /// contains at least `n` elements, otherwise it contains all of the
1246 /// (fewer than `n`) elements of the original iterator.
1253 /// let a = [1, 2, 3];
1255 /// let mut iter = a.iter().take(2);
1257 /// assert_eq!(iter.next(), Some(&1));
1258 /// assert_eq!(iter.next(), Some(&2));
1259 /// assert_eq!(iter.next(), None);
1262 /// `take()` is often used with an infinite iterator, to make it finite:
1265 /// let mut iter = (0..).take(3);
1267 /// assert_eq!(iter.next(), Some(0));
1268 /// assert_eq!(iter.next(), Some(1));
1269 /// assert_eq!(iter.next(), Some(2));
1270 /// assert_eq!(iter.next(), None);
1273 /// If less than `n` elements are available,
1274 /// `take` will limit itself to the size of the underlying iterator:
1277 /// let v = vec![1, 2];
1278 /// let mut iter = v.into_iter().take(5);
1279 /// assert_eq!(iter.next(), Some(1));
1280 /// assert_eq!(iter.next(), Some(2));
1281 /// assert_eq!(iter.next(), None);
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 fn take(self, n: usize) -> Take<Self>
1292 /// An iterator adapter similar to [`fold`] that holds internal state and
1293 /// produces a new iterator.
1295 /// [`fold`]: Iterator::fold
1297 /// `scan()` takes two arguments: an initial value which seeds the internal
1298 /// state, and a closure with two arguments, the first being a mutable
1299 /// reference to the internal state and the second an iterator element.
1300 /// The closure can assign to the internal state to share state between
1303 /// On iteration, the closure will be applied to each element of the
1304 /// iterator and the return value from the closure, an [`Option`], is
1305 /// yielded by the iterator.
1312 /// let a = [1, 2, 3];
1314 /// let mut iter = a.iter().scan(1, |state, &x| {
1315 /// // each iteration, we'll multiply the state by the element
1316 /// *state = *state * x;
1318 /// // then, we'll yield the negation of the state
1322 /// assert_eq!(iter.next(), Some(-1));
1323 /// assert_eq!(iter.next(), Some(-2));
1324 /// assert_eq!(iter.next(), Some(-6));
1325 /// assert_eq!(iter.next(), None);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1332 F: FnMut(&mut St, Self::Item) -> Option<B>,
1334 Scan::new(self, initial_state, f)
1337 /// Creates an iterator that works like map, but flattens nested structure.
1339 /// The [`map`] adapter is very useful, but only when the closure
1340 /// argument produces values. If it produces an iterator instead, there's
1341 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1344 /// You can think of `flat_map(f)` as the semantic equivalent
1345 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1347 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1348 /// one item for each element, and `flat_map()`'s closure returns an
1349 /// iterator for each element.
1351 /// [`map`]: Iterator::map
1352 /// [`flatten`]: Iterator::flatten
1359 /// let words = ["alpha", "beta", "gamma"];
1361 /// // chars() returns an iterator
1362 /// let merged: String = words.iter()
1363 /// .flat_map(|s| s.chars())
1365 /// assert_eq!(merged, "alphabetagamma");
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1373 F: FnMut(Self::Item) -> U,
1375 FlatMap::new(self, f)
1378 /// Creates an iterator that flattens nested structure.
1380 /// This is useful when you have an iterator of iterators or an iterator of
1381 /// things that can be turned into iterators and you want to remove one
1382 /// level of indirection.
1389 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1390 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1391 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1394 /// Mapping and then flattening:
1397 /// let words = ["alpha", "beta", "gamma"];
1399 /// // chars() returns an iterator
1400 /// let merged: String = words.iter()
1401 /// .map(|s| s.chars())
1404 /// assert_eq!(merged, "alphabetagamma");
1407 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1408 /// in this case since it conveys intent more clearly:
1411 /// let words = ["alpha", "beta", "gamma"];
1413 /// // chars() returns an iterator
1414 /// let merged: String = words.iter()
1415 /// .flat_map(|s| s.chars())
1417 /// assert_eq!(merged, "alphabetagamma");
1420 /// Flattening only removes one level of nesting at a time:
1423 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1425 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1426 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1428 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1429 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1432 /// Here we see that `flatten()` does not perform a "deep" flatten.
1433 /// Instead, only one level of nesting is removed. That is, if you
1434 /// `flatten()` a three-dimensional array, the result will be
1435 /// two-dimensional and not one-dimensional. To get a one-dimensional
1436 /// structure, you have to `flatten()` again.
1438 /// [`flat_map()`]: Iterator::flat_map
1440 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1441 fn flatten(self) -> Flatten<Self>
1444 Self::Item: IntoIterator,
1449 /// Creates an iterator which ends after the first [`None`].
1451 /// After an iterator returns [`None`], future calls may or may not yield
1452 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1453 /// [`None`] is given, it will always return [`None`] forever.
1455 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1456 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1457 /// if the [`FusedIterator`] trait is improperly implemented.
1459 /// [`Some(T)`]: Some
1460 /// [`FusedIterator`]: crate::iter::FusedIterator
1467 /// // an iterator which alternates between Some and None
1468 /// struct Alternate {
1472 /// impl Iterator for Alternate {
1473 /// type Item = i32;
1475 /// fn next(&mut self) -> Option<i32> {
1476 /// let val = self.state;
1477 /// self.state = self.state + 1;
1479 /// // if it's even, Some(i32), else None
1480 /// if val % 2 == 0 {
1488 /// let mut iter = Alternate { state: 0 };
1490 /// // we can see our iterator going back and forth
1491 /// assert_eq!(iter.next(), Some(0));
1492 /// assert_eq!(iter.next(), None);
1493 /// assert_eq!(iter.next(), Some(2));
1494 /// assert_eq!(iter.next(), None);
1496 /// // however, once we fuse it...
1497 /// let mut iter = iter.fuse();
1499 /// assert_eq!(iter.next(), Some(4));
1500 /// assert_eq!(iter.next(), None);
1502 /// // it will always return `None` after the first time.
1503 /// assert_eq!(iter.next(), None);
1504 /// assert_eq!(iter.next(), None);
1505 /// assert_eq!(iter.next(), None);
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 fn fuse(self) -> Fuse<Self>
1516 /// Does something with each element of an iterator, passing the value on.
1518 /// When using iterators, you'll often chain several of them together.
1519 /// While working on such code, you might want to check out what's
1520 /// happening at various parts in the pipeline. To do that, insert
1521 /// a call to `inspect()`.
1523 /// It's more common for `inspect()` to be used as a debugging tool than to
1524 /// exist in your final code, but applications may find it useful in certain
1525 /// situations when errors need to be logged before being discarded.
1532 /// let a = [1, 4, 2, 3];
1534 /// // this iterator sequence is complex.
1535 /// let sum = a.iter()
1537 /// .filter(|x| x % 2 == 0)
1538 /// .fold(0, |sum, i| sum + i);
1540 /// println!("{}", sum);
1542 /// // let's add some inspect() calls to investigate what's happening
1543 /// let sum = a.iter()
1545 /// .inspect(|x| println!("about to filter: {}", x))
1546 /// .filter(|x| x % 2 == 0)
1547 /// .inspect(|x| println!("made it through filter: {}", x))
1548 /// .fold(0, |sum, i| sum + i);
1550 /// println!("{}", sum);
1553 /// This will print:
1557 /// about to filter: 1
1558 /// about to filter: 4
1559 /// made it through filter: 4
1560 /// about to filter: 2
1561 /// made it through filter: 2
1562 /// about to filter: 3
1566 /// Logging errors before discarding them:
1569 /// let lines = ["1", "2", "a"];
1571 /// let sum: i32 = lines
1573 /// .map(|line| line.parse::<i32>())
1574 /// .inspect(|num| {
1575 /// if let Err(ref e) = *num {
1576 /// println!("Parsing error: {}", e);
1579 /// .filter_map(Result::ok)
1582 /// println!("Sum: {}", sum);
1585 /// This will print:
1588 /// Parsing error: invalid digit found in string
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1596 F: FnMut(&Self::Item),
1598 Inspect::new(self, f)
1601 /// Borrows an iterator, rather than consuming it.
1603 /// This is useful to allow applying iterator adapters while still
1604 /// retaining ownership of the original iterator.
1611 /// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
1613 /// // Take the first two words.
1614 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1615 /// assert_eq!(hello_world, vec!["hello", "world"]);
1617 /// // Collect the rest of the words.
1618 /// // We can only do this because we used `by_ref` earlier.
1619 /// let of_rust: Vec<_> = words.collect();
1620 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 fn by_ref(&mut self) -> &mut Self
1630 /// Transforms an iterator into a collection.
1632 /// `collect()` can take anything iterable, and turn it into a relevant
1633 /// collection. This is one of the more powerful methods in the standard
1634 /// library, used in a variety of contexts.
1636 /// The most basic pattern in which `collect()` is used is to turn one
1637 /// collection into another. You take a collection, call [`iter`] on it,
1638 /// do a bunch of transformations, and then `collect()` at the end.
1640 /// `collect()` can also create instances of types that are not typical
1641 /// collections. For example, a [`String`] can be built from [`char`]s,
1642 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1643 /// into `Result<Collection<T>, E>`. See the examples below for more.
1645 /// Because `collect()` is so general, it can cause problems with type
1646 /// inference. As such, `collect()` is one of the few times you'll see
1647 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1648 /// helps the inference algorithm understand specifically which collection
1649 /// you're trying to collect into.
1656 /// let a = [1, 2, 3];
1658 /// let doubled: Vec<i32> = a.iter()
1659 /// .map(|&x| x * 2)
1662 /// assert_eq!(vec![2, 4, 6], doubled);
1665 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1666 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1668 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1671 /// use std::collections::VecDeque;
1673 /// let a = [1, 2, 3];
1675 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1677 /// assert_eq!(2, doubled[0]);
1678 /// assert_eq!(4, doubled[1]);
1679 /// assert_eq!(6, doubled[2]);
1682 /// Using the 'turbofish' instead of annotating `doubled`:
1685 /// let a = [1, 2, 3];
1687 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1689 /// assert_eq!(vec![2, 4, 6], doubled);
1692 /// Because `collect()` only cares about what you're collecting into, you can
1693 /// still use a partial type hint, `_`, with the turbofish:
1696 /// let a = [1, 2, 3];
1698 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1700 /// assert_eq!(vec![2, 4, 6], doubled);
1703 /// Using `collect()` to make a [`String`]:
1706 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1708 /// let hello: String = chars.iter()
1709 /// .map(|&x| x as u8)
1710 /// .map(|x| (x + 1) as char)
1713 /// assert_eq!("hello", hello);
1716 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1717 /// see if any of them failed:
1720 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1722 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1724 /// // gives us the first error
1725 /// assert_eq!(Err("nope"), result);
1727 /// let results = [Ok(1), Ok(3)];
1729 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1731 /// // gives us the list of answers
1732 /// assert_eq!(Ok(vec![1, 3]), result);
1735 /// [`iter`]: Iterator::next
1736 /// [`String`]: ../../std/string/struct.String.html
1737 /// [`char`]: type@char
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1741 fn collect<B: FromIterator<Self::Item>>(self) -> B
1745 FromIterator::from_iter(self)
1748 /// Consumes an iterator, creating two collections from it.
1750 /// The predicate passed to `partition()` can return `true`, or `false`.
1751 /// `partition()` returns a pair, all of the elements for which it returned
1752 /// `true`, and all of the elements for which it returned `false`.
1754 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1756 /// [`is_partitioned()`]: Iterator::is_partitioned
1757 /// [`partition_in_place()`]: Iterator::partition_in_place
1764 /// let a = [1, 2, 3];
1766 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1768 /// .partition(|&n| n % 2 == 0);
1770 /// assert_eq!(even, vec![2]);
1771 /// assert_eq!(odd, vec![1, 3]);
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 fn partition<B, F>(self, f: F) -> (B, B)
1777 B: Default + Extend<Self::Item>,
1778 F: FnMut(&Self::Item) -> bool,
1781 fn extend<'a, T, B: Extend<T>>(
1782 mut f: impl FnMut(&T) -> bool + 'a,
1785 ) -> impl FnMut((), T) + 'a {
1790 right.extend_one(x);
1795 let mut left: B = Default::default();
1796 let mut right: B = Default::default();
1798 self.fold((), extend(f, &mut left, &mut right));
1803 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1804 /// such that all those that return `true` precede all those that return `false`.
1805 /// Returns the number of `true` elements found.
1807 /// The relative order of partitioned items is not maintained.
1809 /// # Current implementation
1810 /// Current algorithms tries finding the first element for which the predicate evaluates
1811 /// to false, and the last element for which it evaluates to true and repeatedly swaps them.
1813 /// Time Complexity: *O*(*N*)
1815 /// See also [`is_partitioned()`] and [`partition()`].
1817 /// [`is_partitioned()`]: Iterator::is_partitioned
1818 /// [`partition()`]: Iterator::partition
1823 /// #![feature(iter_partition_in_place)]
1825 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1827 /// // Partition in-place between evens and odds
1828 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1830 /// assert_eq!(i, 3);
1831 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1832 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1834 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1835 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1837 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1838 P: FnMut(&T) -> bool,
1840 // FIXME: should we worry about the count overflowing? The only way to have more than
1841 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1843 // These closure "factory" functions exist to avoid genericity in `Self`.
1847 predicate: &'a mut impl FnMut(&T) -> bool,
1848 true_count: &'a mut usize,
1849 ) -> impl FnMut(&&mut T) -> bool + 'a {
1851 let p = predicate(&**x);
1852 *true_count += p as usize;
1858 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1859 move |x| predicate(&**x)
1862 // Repeatedly find the first `false` and swap it with the last `true`.
1863 let mut true_count = 0;
1864 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1865 if let Some(tail) = self.rfind(is_true(predicate)) {
1866 crate::mem::swap(head, tail);
1875 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1876 /// such that all those that return `true` precede all those that return `false`.
1878 /// See also [`partition()`] and [`partition_in_place()`].
1880 /// [`partition()`]: Iterator::partition
1881 /// [`partition_in_place()`]: Iterator::partition_in_place
1886 /// #![feature(iter_is_partitioned)]
1888 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1889 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1891 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1892 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1895 P: FnMut(Self::Item) -> bool,
1897 // Either all items test `true`, or the first clause stops at `false`
1898 // and we check that there are no more `true` items after that.
1899 self.all(&mut predicate) || !self.any(predicate)
1902 /// An iterator method that applies a function as long as it returns
1903 /// successfully, producing a single, final value.
1905 /// `try_fold()` takes two arguments: an initial value, and a closure with
1906 /// two arguments: an 'accumulator', and an element. The closure either
1907 /// returns successfully, with the value that the accumulator should have
1908 /// for the next iteration, or it returns failure, with an error value that
1909 /// is propagated back to the caller immediately (short-circuiting).
1911 /// The initial value is the value the accumulator will have on the first
1912 /// call. If applying the closure succeeded against every element of the
1913 /// iterator, `try_fold()` returns the final accumulator as success.
1915 /// Folding is useful whenever you have a collection of something, and want
1916 /// to produce a single value from it.
1918 /// # Note to Implementors
1920 /// Several of the other (forward) methods have default implementations in
1921 /// terms of this one, so try to implement this explicitly if it can
1922 /// do something better than the default `for` loop implementation.
1924 /// In particular, try to have this call `try_fold()` on the internal parts
1925 /// from which this iterator is composed. If multiple calls are needed,
1926 /// the `?` operator may be convenient for chaining the accumulator value
1927 /// along, but beware any invariants that need to be upheld before those
1928 /// early returns. This is a `&mut self` method, so iteration needs to be
1929 /// resumable after hitting an error here.
1936 /// let a = [1, 2, 3];
1938 /// // the checked sum of all of the elements of the array
1939 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1941 /// assert_eq!(sum, Some(6));
1944 /// Short-circuiting:
1947 /// let a = [10, 20, 30, 100, 40, 50];
1948 /// let mut it = a.iter();
1950 /// // This sum overflows when adding the 100 element
1951 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1952 /// assert_eq!(sum, None);
1954 /// // Because it short-circuited, the remaining elements are still
1955 /// // available through the iterator.
1956 /// assert_eq!(it.len(), 2);
1957 /// assert_eq!(it.next(), Some(&40));
1960 /// While you cannot `break` from a closure, the [`crate::ops::ControlFlow`]
1961 /// type allows a similar idea:
1964 /// use std::ops::ControlFlow;
1966 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
1967 /// if let Some(next) = prev.checked_add(x) {
1968 /// ControlFlow::Continue(next)
1970 /// ControlFlow::Break(prev)
1973 /// assert_eq!(triangular, ControlFlow::Break(120));
1975 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
1976 /// if let Some(next) = prev.checked_add(x) {
1977 /// ControlFlow::Continue(next)
1979 /// ControlFlow::Break(prev)
1982 /// assert_eq!(triangular, ControlFlow::Continue(435));
1985 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1986 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1989 F: FnMut(B, Self::Item) -> R,
1992 let mut accum = init;
1993 while let Some(x) = self.next() {
1994 accum = f(accum, x)?;
1999 /// An iterator method that applies a fallible function to each item in the
2000 /// iterator, stopping at the first error and returning that error.
2002 /// This can also be thought of as the fallible form of [`for_each()`]
2003 /// or as the stateless version of [`try_fold()`].
2005 /// [`for_each()`]: Iterator::for_each
2006 /// [`try_fold()`]: Iterator::try_fold
2011 /// use std::fs::rename;
2012 /// use std::io::{stdout, Write};
2013 /// use std::path::Path;
2015 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2017 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
2018 /// assert!(res.is_ok());
2020 /// let mut it = data.iter().cloned();
2021 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2022 /// assert!(res.is_err());
2023 /// // It short-circuited, so the remaining items are still in the iterator:
2024 /// assert_eq!(it.next(), Some("stale_bread.json"));
2027 /// The [`crate::ops::ControlFlow`] type can be used with this method for the
2028 /// situations in which you'd use `break` and `continue` in a normal loop:
2031 /// use std::ops::ControlFlow;
2033 /// let r = (2..100).try_for_each(|x| {
2034 /// if 323 % x == 0 {
2035 /// return ControlFlow::Break(x)
2038 /// ControlFlow::Continue(())
2040 /// assert_eq!(r, ControlFlow::Break(17));
2043 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2044 fn try_for_each<F, R>(&mut self, f: F) -> R
2047 F: FnMut(Self::Item) -> R,
2048 R: Try<Output = ()>,
2051 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2055 self.try_fold((), call(f))
2058 /// Folds every element into an accumulator by applying an operation,
2059 /// returning the final result.
2061 /// `fold()` takes two arguments: an initial value, and a closure with two
2062 /// arguments: an 'accumulator', and an element. The closure returns the value that
2063 /// the accumulator should have for the next iteration.
2065 /// The initial value is the value the accumulator will have on the first
2068 /// After applying this closure to every element of the iterator, `fold()`
2069 /// returns the accumulator.
2071 /// This operation is sometimes called 'reduce' or 'inject'.
2073 /// Folding is useful whenever you have a collection of something, and want
2074 /// to produce a single value from it.
2076 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2077 /// might not terminate for infinite iterators, even on traits for which a
2078 /// result is determinable in finite time.
2080 /// Note: [`reduce()`] can be used to use the first element as the initial
2081 /// value, if the accumulator type and item type is the same.
2083 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2084 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2085 /// operators like `-` the order will affect the final result.
2086 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2088 /// # Note to Implementors
2090 /// Several of the other (forward) methods have default implementations in
2091 /// terms of this one, so try to implement this explicitly if it can
2092 /// do something better than the default `for` loop implementation.
2094 /// In particular, try to have this call `fold()` on the internal parts
2095 /// from which this iterator is composed.
2102 /// let a = [1, 2, 3];
2104 /// // the sum of all of the elements of the array
2105 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2107 /// assert_eq!(sum, 6);
2110 /// Let's walk through each step of the iteration here:
2112 /// | element | acc | x | result |
2113 /// |---------|-----|---|--------|
2115 /// | 1 | 0 | 1 | 1 |
2116 /// | 2 | 1 | 2 | 3 |
2117 /// | 3 | 3 | 3 | 6 |
2119 /// And so, our final result, `6`.
2121 /// This example demonstrates the left-associative nature of `fold()`:
2122 /// it builds a string, starting with an initial value
2123 /// and continuing with each element from the front until the back:
2126 /// let numbers = [1, 2, 3, 4, 5];
2128 /// let zero = "0".to_string();
2130 /// let result = numbers.iter().fold(zero, |acc, &x| {
2131 /// format!("({} + {})", acc, x)
2134 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2136 /// It's common for people who haven't used iterators a lot to
2137 /// use a `for` loop with a list of things to build up a result. Those
2138 /// can be turned into `fold()`s:
2140 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2143 /// let numbers = [1, 2, 3, 4, 5];
2145 /// let mut result = 0;
2148 /// for i in &numbers {
2149 /// result = result + i;
2153 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2155 /// // they're the same
2156 /// assert_eq!(result, result2);
2159 /// [`reduce()`]: Iterator::reduce
2160 #[doc(alias = "inject", alias = "foldl")]
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2166 F: FnMut(B, Self::Item) -> B,
2168 let mut accum = init;
2169 while let Some(x) = self.next() {
2170 accum = f(accum, x);
2175 /// Reduces the elements to a single one, by repeatedly applying a reducing
2178 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2179 /// result of the reduction.
2181 /// For iterators with at least one element, this is the same as [`fold()`]
2182 /// with the first element of the iterator as the initial value, folding
2183 /// every subsequent element into it.
2185 /// [`fold()`]: Iterator::fold
2189 /// Find the maximum value:
2192 /// fn find_max<I>(iter: I) -> Option<I::Item>
2193 /// where I: Iterator,
2196 /// iter.reduce(|a, b| {
2197 /// if a >= b { a } else { b }
2200 /// let a = [10, 20, 5, -23, 0];
2201 /// let b: [u32; 0] = [];
2203 /// assert_eq!(find_max(a.iter()), Some(&20));
2204 /// assert_eq!(find_max(b.iter()), None);
2207 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2208 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2211 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2213 let first = self.next()?;
2214 Some(self.fold(first, f))
2217 /// Tests if every element of the iterator matches a predicate.
2219 /// `all()` takes a closure that returns `true` or `false`. It applies
2220 /// this closure to each element of the iterator, and if they all return
2221 /// `true`, then so does `all()`. If any of them return `false`, it
2222 /// returns `false`.
2224 /// `all()` is short-circuiting; in other words, it will stop processing
2225 /// as soon as it finds a `false`, given that no matter what else happens,
2226 /// the result will also be `false`.
2228 /// An empty iterator returns `true`.
2235 /// let a = [1, 2, 3];
2237 /// assert!(a.iter().all(|&x| x > 0));
2239 /// assert!(!a.iter().all(|&x| x > 2));
2242 /// Stopping at the first `false`:
2245 /// let a = [1, 2, 3];
2247 /// let mut iter = a.iter();
2249 /// assert!(!iter.all(|&x| x != 2));
2251 /// // we can still use `iter`, as there are more elements.
2252 /// assert_eq!(iter.next(), Some(&3));
2255 #[stable(feature = "rust1", since = "1.0.0")]
2256 fn all<F>(&mut self, f: F) -> bool
2259 F: FnMut(Self::Item) -> bool,
2262 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2264 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2267 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2270 /// Tests if any element of the iterator matches a predicate.
2272 /// `any()` takes a closure that returns `true` or `false`. It applies
2273 /// this closure to each element of the iterator, and if any of them return
2274 /// `true`, then so does `any()`. If they all return `false`, it
2275 /// returns `false`.
2277 /// `any()` is short-circuiting; in other words, it will stop processing
2278 /// as soon as it finds a `true`, given that no matter what else happens,
2279 /// the result will also be `true`.
2281 /// An empty iterator returns `false`.
2288 /// let a = [1, 2, 3];
2290 /// assert!(a.iter().any(|&x| x > 0));
2292 /// assert!(!a.iter().any(|&x| x > 5));
2295 /// Stopping at the first `true`:
2298 /// let a = [1, 2, 3];
2300 /// let mut iter = a.iter();
2302 /// assert!(iter.any(|&x| x != 2));
2304 /// // we can still use `iter`, as there are more elements.
2305 /// assert_eq!(iter.next(), Some(&2));
2308 #[stable(feature = "rust1", since = "1.0.0")]
2309 fn any<F>(&mut self, f: F) -> bool
2312 F: FnMut(Self::Item) -> bool,
2315 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2317 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2321 self.try_fold((), check(f)) == ControlFlow::BREAK
2324 /// Searches for an element of an iterator that satisfies a predicate.
2326 /// `find()` takes a closure that returns `true` or `false`. It applies
2327 /// this closure to each element of the iterator, and if any of them return
2328 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2329 /// `false`, it returns [`None`].
2331 /// `find()` is short-circuiting; in other words, it will stop processing
2332 /// as soon as the closure returns `true`.
2334 /// Because `find()` takes a reference, and many iterators iterate over
2335 /// references, this leads to a possibly confusing situation where the
2336 /// argument is a double reference. You can see this effect in the
2337 /// examples below, with `&&x`.
2339 /// [`Some(element)`]: Some
2346 /// let a = [1, 2, 3];
2348 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2350 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2353 /// Stopping at the first `true`:
2356 /// let a = [1, 2, 3];
2358 /// let mut iter = a.iter();
2360 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2362 /// // we can still use `iter`, as there are more elements.
2363 /// assert_eq!(iter.next(), Some(&3));
2366 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2372 P: FnMut(&Self::Item) -> bool,
2375 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2377 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2381 self.try_fold((), check(predicate)).break_value()
2384 /// Applies function to the elements of iterator and returns
2385 /// the first non-none result.
2387 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2392 /// let a = ["lol", "NaN", "2", "5"];
2394 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2396 /// assert_eq!(first_number, Some(2));
2399 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2400 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2403 F: FnMut(Self::Item) -> Option<B>,
2406 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2407 move |(), x| match f(x) {
2408 Some(x) => ControlFlow::Break(x),
2409 None => ControlFlow::CONTINUE,
2413 self.try_fold((), check(f)).break_value()
2416 /// Applies function to the elements of iterator and returns
2417 /// the first true result or the first error.
2422 /// #![feature(try_find)]
2424 /// let a = ["1", "2", "lol", "NaN", "5"];
2426 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2427 /// Ok(s.parse::<i32>()? == search)
2430 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2431 /// assert_eq!(result, Ok(Some(&"2")));
2433 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2434 /// assert!(result.is_err());
2437 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2438 fn try_find<F, R, E>(&mut self, f: F) -> Result<Option<Self::Item>, E>
2441 F: FnMut(&Self::Item) -> R,
2442 R: Try<Output = bool>,
2443 // FIXME: This bound is rather strange, but means minimal breakage on nightly.
2444 // See #85115 for the issue tracking a holistic solution for this and try_map.
2445 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2448 fn check<F, T, R, E>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, E>>
2451 R: Try<Output = bool>,
2452 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2454 move |(), x| match f(&x).branch() {
2455 ControlFlow::Continue(false) => ControlFlow::CONTINUE,
2456 ControlFlow::Continue(true) => ControlFlow::Break(Ok(x)),
2457 ControlFlow::Break(Err(x)) => ControlFlow::Break(Err(x)),
2461 self.try_fold((), check(f)).break_value().transpose()
2464 /// Searches for an element in an iterator, returning its index.
2466 /// `position()` takes a closure that returns `true` or `false`. It applies
2467 /// this closure to each element of the iterator, and if one of them
2468 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2469 /// them return `false`, it returns [`None`].
2471 /// `position()` is short-circuiting; in other words, it will stop
2472 /// processing as soon as it finds a `true`.
2474 /// # Overflow Behavior
2476 /// The method does no guarding against overflows, so if there are more
2477 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2478 /// result or panics. If debug assertions are enabled, a panic is
2483 /// This function might panic if the iterator has more than `usize::MAX`
2484 /// non-matching elements.
2486 /// [`Some(index)`]: Some
2493 /// let a = [1, 2, 3];
2495 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2497 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2500 /// Stopping at the first `true`:
2503 /// let a = [1, 2, 3, 4];
2505 /// let mut iter = a.iter();
2507 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2509 /// // we can still use `iter`, as there are more elements.
2510 /// assert_eq!(iter.next(), Some(&3));
2512 /// // The returned index depends on iterator state
2513 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2517 #[stable(feature = "rust1", since = "1.0.0")]
2518 fn position<P>(&mut self, predicate: P) -> Option<usize>
2521 P: FnMut(Self::Item) -> bool,
2525 mut predicate: impl FnMut(T) -> bool,
2526 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2527 #[rustc_inherit_overflow_checks]
2529 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2533 self.try_fold(0, check(predicate)).break_value()
2536 /// Searches for an element in an iterator from the right, returning its
2539 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2540 /// this closure to each element of the iterator, starting from the end,
2541 /// and if one of them returns `true`, then `rposition()` returns
2542 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2544 /// `rposition()` is short-circuiting; in other words, it will stop
2545 /// processing as soon as it finds a `true`.
2547 /// [`Some(index)`]: Some
2554 /// let a = [1, 2, 3];
2556 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2558 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2561 /// Stopping at the first `true`:
2564 /// let a = [1, 2, 3];
2566 /// let mut iter = a.iter();
2568 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2570 /// // we can still use `iter`, as there are more elements.
2571 /// assert_eq!(iter.next(), Some(&1));
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2577 P: FnMut(Self::Item) -> bool,
2578 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2580 // No need for an overflow check here, because `ExactSizeIterator`
2581 // implies that the number of elements fits into a `usize`.
2584 mut predicate: impl FnMut(T) -> bool,
2585 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2588 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2593 self.try_rfold(n, check(predicate)).break_value()
2596 /// Returns the maximum element of an iterator.
2598 /// If several elements are equally maximum, the last element is
2599 /// returned. If the iterator is empty, [`None`] is returned.
2601 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2602 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2605 /// vec![2.4, f32::NAN, 1.3]
2607 /// .reduce(f32::max)
2618 /// let a = [1, 2, 3];
2619 /// let b: Vec<u32> = Vec::new();
2621 /// assert_eq!(a.iter().max(), Some(&3));
2622 /// assert_eq!(b.iter().max(), None);
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 fn max(self) -> Option<Self::Item>
2631 self.max_by(Ord::cmp)
2634 /// Returns the minimum element of an iterator.
2636 /// If several elements are equally minimum, the first element is returned.
2637 /// If the iterator is empty, [`None`] is returned.
2639 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2640 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2643 /// vec![2.4, f32::NAN, 1.3]
2645 /// .reduce(f32::min)
2656 /// let a = [1, 2, 3];
2657 /// let b: Vec<u32> = Vec::new();
2659 /// assert_eq!(a.iter().min(), Some(&1));
2660 /// assert_eq!(b.iter().min(), None);
2663 #[stable(feature = "rust1", since = "1.0.0")]
2664 fn min(self) -> Option<Self::Item>
2669 self.min_by(Ord::cmp)
2672 /// Returns the element that gives the maximum value from the
2673 /// specified function.
2675 /// If several elements are equally maximum, the last element is
2676 /// returned. If the iterator is empty, [`None`] is returned.
2681 /// let a = [-3_i32, 0, 1, 5, -10];
2682 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2685 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2686 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2689 F: FnMut(&Self::Item) -> B,
2692 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2697 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2701 let (_, x) = self.map(key(f)).max_by(compare)?;
2705 /// Returns the element that gives the maximum value with respect to the
2706 /// specified comparison function.
2708 /// If several elements are equally maximum, the last element is
2709 /// returned. If the iterator is empty, [`None`] is returned.
2714 /// let a = [-3_i32, 0, 1, 5, -10];
2715 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2718 #[stable(feature = "iter_max_by", since = "1.15.0")]
2719 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2722 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2725 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2726 move |x, y| cmp::max_by(x, y, &mut compare)
2729 self.reduce(fold(compare))
2732 /// Returns the element that gives the minimum value from the
2733 /// specified function.
2735 /// If several elements are equally minimum, the first element is
2736 /// returned. If the iterator is empty, [`None`] is returned.
2741 /// let a = [-3_i32, 0, 1, 5, -10];
2742 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2745 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2746 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2749 F: FnMut(&Self::Item) -> B,
2752 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2757 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2761 let (_, x) = self.map(key(f)).min_by(compare)?;
2765 /// Returns the element that gives the minimum value with respect to the
2766 /// specified comparison function.
2768 /// If several elements are equally minimum, the first element is
2769 /// returned. If the iterator is empty, [`None`] is returned.
2774 /// let a = [-3_i32, 0, 1, 5, -10];
2775 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2778 #[stable(feature = "iter_min_by", since = "1.15.0")]
2779 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2782 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2785 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2786 move |x, y| cmp::min_by(x, y, &mut compare)
2789 self.reduce(fold(compare))
2792 /// Reverses an iterator's direction.
2794 /// Usually, iterators iterate from left to right. After using `rev()`,
2795 /// an iterator will instead iterate from right to left.
2797 /// This is only possible if the iterator has an end, so `rev()` only
2798 /// works on [`DoubleEndedIterator`]s.
2803 /// let a = [1, 2, 3];
2805 /// let mut iter = a.iter().rev();
2807 /// assert_eq!(iter.next(), Some(&3));
2808 /// assert_eq!(iter.next(), Some(&2));
2809 /// assert_eq!(iter.next(), Some(&1));
2811 /// assert_eq!(iter.next(), None);
2814 #[doc(alias = "reverse")]
2815 #[stable(feature = "rust1", since = "1.0.0")]
2816 fn rev(self) -> Rev<Self>
2818 Self: Sized + DoubleEndedIterator,
2823 /// Converts an iterator of pairs into a pair of containers.
2825 /// `unzip()` consumes an entire iterator of pairs, producing two
2826 /// collections: one from the left elements of the pairs, and one
2827 /// from the right elements.
2829 /// This function is, in some sense, the opposite of [`zip`].
2831 /// [`zip`]: Iterator::zip
2838 /// let a = [(1, 2), (3, 4)];
2840 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2842 /// assert_eq!(left, [1, 3]);
2843 /// assert_eq!(right, [2, 4]);
2845 #[stable(feature = "rust1", since = "1.0.0")]
2846 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2848 FromA: Default + Extend<A>,
2849 FromB: Default + Extend<B>,
2850 Self: Sized + Iterator<Item = (A, B)>,
2852 fn extend<'a, A, B>(
2853 ts: &'a mut impl Extend<A>,
2854 us: &'a mut impl Extend<B>,
2855 ) -> impl FnMut((), (A, B)) + 'a {
2862 let mut ts: FromA = Default::default();
2863 let mut us: FromB = Default::default();
2865 let (lower_bound, _) = self.size_hint();
2866 if lower_bound > 0 {
2867 ts.extend_reserve(lower_bound);
2868 us.extend_reserve(lower_bound);
2871 self.fold((), extend(&mut ts, &mut us));
2876 /// Creates an iterator which copies all of its elements.
2878 /// This is useful when you have an iterator over `&T`, but you need an
2879 /// iterator over `T`.
2886 /// let a = [1, 2, 3];
2888 /// let v_copied: Vec<_> = a.iter().copied().collect();
2890 /// // copied is the same as .map(|&x| x)
2891 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2893 /// assert_eq!(v_copied, vec![1, 2, 3]);
2894 /// assert_eq!(v_map, vec![1, 2, 3]);
2896 #[stable(feature = "iter_copied", since = "1.36.0")]
2897 fn copied<'a, T: 'a>(self) -> Copied<Self>
2899 Self: Sized + Iterator<Item = &'a T>,
2905 /// Creates an iterator which [`clone`]s all of its elements.
2907 /// This is useful when you have an iterator over `&T`, but you need an
2908 /// iterator over `T`.
2910 /// [`clone`]: Clone::clone
2917 /// let a = [1, 2, 3];
2919 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2921 /// // cloned is the same as .map(|&x| x), for integers
2922 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2924 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2925 /// assert_eq!(v_map, vec![1, 2, 3]);
2927 #[stable(feature = "rust1", since = "1.0.0")]
2928 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2930 Self: Sized + Iterator<Item = &'a T>,
2936 /// Repeats an iterator endlessly.
2938 /// Instead of stopping at [`None`], the iterator will instead start again,
2939 /// from the beginning. After iterating again, it will start at the
2940 /// beginning again. And again. And again. Forever.
2947 /// let a = [1, 2, 3];
2949 /// let mut it = a.iter().cycle();
2951 /// assert_eq!(it.next(), Some(&1));
2952 /// assert_eq!(it.next(), Some(&2));
2953 /// assert_eq!(it.next(), Some(&3));
2954 /// assert_eq!(it.next(), Some(&1));
2955 /// assert_eq!(it.next(), Some(&2));
2956 /// assert_eq!(it.next(), Some(&3));
2957 /// assert_eq!(it.next(), Some(&1));
2959 #[stable(feature = "rust1", since = "1.0.0")]
2961 fn cycle(self) -> Cycle<Self>
2963 Self: Sized + Clone,
2968 /// Sums the elements of an iterator.
2970 /// Takes each element, adds them together, and returns the result.
2972 /// An empty iterator returns the zero value of the type.
2976 /// When calling `sum()` and a primitive integer type is being returned, this
2977 /// method will panic if the computation overflows and debug assertions are
2985 /// let a = [1, 2, 3];
2986 /// let sum: i32 = a.iter().sum();
2988 /// assert_eq!(sum, 6);
2990 #[stable(feature = "iter_arith", since = "1.11.0")]
2991 fn sum<S>(self) -> S
2999 /// Iterates over the entire iterator, multiplying all the elements
3001 /// An empty iterator returns the one value of the type.
3005 /// When calling `product()` and a primitive integer type is being returned,
3006 /// method will panic if the computation overflows and debug assertions are
3012 /// fn factorial(n: u32) -> u32 {
3013 /// (1..=n).product()
3015 /// assert_eq!(factorial(0), 1);
3016 /// assert_eq!(factorial(1), 1);
3017 /// assert_eq!(factorial(5), 120);
3019 #[stable(feature = "iter_arith", since = "1.11.0")]
3020 fn product<P>(self) -> P
3023 P: Product<Self::Item>,
3025 Product::product(self)
3028 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3034 /// use std::cmp::Ordering;
3036 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3037 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3038 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3040 #[stable(feature = "iter_order", since = "1.5.0")]
3041 fn cmp<I>(self, other: I) -> Ordering
3043 I: IntoIterator<Item = Self::Item>,
3047 self.cmp_by(other, |x, y| x.cmp(&y))
3050 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3051 /// of another with respect to the specified comparison function.
3058 /// #![feature(iter_order_by)]
3060 /// use std::cmp::Ordering;
3062 /// let xs = [1, 2, 3, 4];
3063 /// let ys = [1, 4, 9, 16];
3065 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3066 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3067 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3069 #[unstable(feature = "iter_order_by", issue = "64295")]
3070 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
3074 F: FnMut(Self::Item, I::Item) -> Ordering,
3076 let mut other = other.into_iter();
3079 let x = match self.next() {
3081 if other.next().is_none() {
3082 return Ordering::Equal;
3084 return Ordering::Less;
3090 let y = match other.next() {
3091 None => return Ordering::Greater,
3096 Ordering::Equal => (),
3097 non_eq => return non_eq,
3102 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3108 /// use std::cmp::Ordering;
3110 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3111 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3112 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3114 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3116 #[stable(feature = "iter_order", since = "1.5.0")]
3117 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3120 Self::Item: PartialOrd<I::Item>,
3123 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3126 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3127 /// of another with respect to the specified comparison function.
3134 /// #![feature(iter_order_by)]
3136 /// use std::cmp::Ordering;
3138 /// let xs = [1.0, 2.0, 3.0, 4.0];
3139 /// let ys = [1.0, 4.0, 9.0, 16.0];
3142 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3143 /// Some(Ordering::Less)
3146 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3147 /// Some(Ordering::Equal)
3150 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3151 /// Some(Ordering::Greater)
3154 #[unstable(feature = "iter_order_by", issue = "64295")]
3155 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3159 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3161 let mut other = other.into_iter();
3164 let x = match self.next() {
3166 if other.next().is_none() {
3167 return Some(Ordering::Equal);
3169 return Some(Ordering::Less);
3175 let y = match other.next() {
3176 None => return Some(Ordering::Greater),
3180 match partial_cmp(x, y) {
3181 Some(Ordering::Equal) => (),
3182 non_eq => return non_eq,
3187 /// Determines if the elements of this [`Iterator`] are equal to those of
3193 /// assert_eq!([1].iter().eq([1].iter()), true);
3194 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3196 #[stable(feature = "iter_order", since = "1.5.0")]
3197 fn eq<I>(self, other: I) -> bool
3200 Self::Item: PartialEq<I::Item>,
3203 self.eq_by(other, |x, y| x == y)
3206 /// Determines if the elements of this [`Iterator`] are equal to those of
3207 /// another with respect to the specified equality function.
3214 /// #![feature(iter_order_by)]
3216 /// let xs = [1, 2, 3, 4];
3217 /// let ys = [1, 4, 9, 16];
3219 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3221 #[unstable(feature = "iter_order_by", issue = "64295")]
3222 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3226 F: FnMut(Self::Item, I::Item) -> bool,
3228 let mut other = other.into_iter();
3231 let x = match self.next() {
3232 None => return other.next().is_none(),
3236 let y = match other.next() {
3237 None => return false,
3247 /// Determines if the elements of this [`Iterator`] are unequal to those of
3253 /// assert_eq!([1].iter().ne([1].iter()), false);
3254 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3256 #[stable(feature = "iter_order", since = "1.5.0")]
3257 fn ne<I>(self, other: I) -> bool
3260 Self::Item: PartialEq<I::Item>,
3266 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3267 /// less than those of another.
3272 /// assert_eq!([1].iter().lt([1].iter()), false);
3273 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3274 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3275 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3277 #[stable(feature = "iter_order", since = "1.5.0")]
3278 fn lt<I>(self, other: I) -> bool
3281 Self::Item: PartialOrd<I::Item>,
3284 self.partial_cmp(other) == Some(Ordering::Less)
3287 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3288 /// less or equal to those of another.
3293 /// assert_eq!([1].iter().le([1].iter()), true);
3294 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3295 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3296 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3298 #[stable(feature = "iter_order", since = "1.5.0")]
3299 fn le<I>(self, other: I) -> bool
3302 Self::Item: PartialOrd<I::Item>,
3305 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3308 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3309 /// greater than those of another.
3314 /// assert_eq!([1].iter().gt([1].iter()), false);
3315 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3316 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3317 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3319 #[stable(feature = "iter_order", since = "1.5.0")]
3320 fn gt<I>(self, other: I) -> bool
3323 Self::Item: PartialOrd<I::Item>,
3326 self.partial_cmp(other) == Some(Ordering::Greater)
3329 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3330 /// greater than or equal to those of another.
3335 /// assert_eq!([1].iter().ge([1].iter()), true);
3336 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3337 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3338 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3340 #[stable(feature = "iter_order", since = "1.5.0")]
3341 fn ge<I>(self, other: I) -> bool
3344 Self::Item: PartialOrd<I::Item>,
3347 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3350 /// Checks if the elements of this iterator are sorted.
3352 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3353 /// iterator yields exactly zero or one element, `true` is returned.
3355 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3356 /// implies that this function returns `false` if any two consecutive items are not
3362 /// #![feature(is_sorted)]
3364 /// assert!([1, 2, 2, 9].iter().is_sorted());
3365 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3366 /// assert!([0].iter().is_sorted());
3367 /// assert!(std::iter::empty::<i32>().is_sorted());
3368 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3371 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3372 fn is_sorted(self) -> bool
3375 Self::Item: PartialOrd,
3377 self.is_sorted_by(PartialOrd::partial_cmp)
3380 /// Checks if the elements of this iterator are sorted using the given comparator function.
3382 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3383 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3384 /// [`is_sorted`]; see its documentation for more information.
3389 /// #![feature(is_sorted)]
3391 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3392 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3393 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3394 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3395 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3398 /// [`is_sorted`]: Iterator::is_sorted
3399 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3400 fn is_sorted_by<F>(mut self, compare: F) -> bool
3403 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3408 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3409 ) -> impl FnMut(T) -> bool + 'a {
3411 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3419 let mut last = match self.next() {
3421 None => return true,
3424 self.all(check(&mut last, compare))
3427 /// Checks if the elements of this iterator are sorted using the given key extraction
3430 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3431 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3432 /// its documentation for more information.
3434 /// [`is_sorted`]: Iterator::is_sorted
3439 /// #![feature(is_sorted)]
3441 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3442 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3445 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3446 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3449 F: FnMut(Self::Item) -> K,
3452 self.map(f).is_sorted()
3455 /// See [TrustedRandomAccess]
3456 // The unusual name is to avoid name collisions in method resolution
3460 #[unstable(feature = "trusted_random_access", issue = "none")]
3461 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3463 Self: TrustedRandomAccessNoCoerce,
3465 unreachable!("Always specialized");
3469 #[stable(feature = "rust1", since = "1.0.0")]
3470 impl<I: Iterator + ?Sized> Iterator for &mut I {
3471 type Item = I::Item;
3472 fn next(&mut self) -> Option<I::Item> {
3475 fn size_hint(&self) -> (usize, Option<usize>) {
3476 (**self).size_hint()
3478 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3479 (**self).advance_by(n)
3481 fn nth(&mut self, n: usize) -> Option<Self::Item> {