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::{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::RangeTo<Idx>",
30 label = "if you meant to iterate until a value, add a starting value",
31 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
32 bounded `Range`: `0..end`"
35 _Self = "std::ops::RangeToInclusive<Idx>",
36 label = "if you meant to iterate until a value (including it), add a starting value",
37 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
38 to have a bounded `RangeInclusive`: `0..=end`"
42 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
45 _Self = "std::string::String",
46 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
50 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
51 syntax `start..end` or the inclusive range syntax `start..=end`"
53 label = "`{Self}` is not an iterator",
54 message = "`{Self}` is not an iterator"
57 #[rustc_diagnostic_item = "Iterator"]
58 #[must_use = "iterators are lazy and do nothing unless consumed"]
60 /// The type of the elements being iterated over.
61 #[stable(feature = "rust1", since = "1.0.0")]
64 /// Advances the iterator and returns the next value.
66 /// Returns [`None`] when iteration is finished. Individual iterator
67 /// implementations may choose to resume iteration, and so calling `next()`
68 /// again may or may not eventually start returning [`Some(Item)`] again at some
71 /// [`Some(Item)`]: Some
78 /// let a = [1, 2, 3];
80 /// let mut iter = a.iter();
82 /// // A call to next() returns the next value...
83 /// assert_eq!(Some(&1), iter.next());
84 /// assert_eq!(Some(&2), iter.next());
85 /// assert_eq!(Some(&3), iter.next());
87 /// // ... and then None once it's over.
88 /// assert_eq!(None, iter.next());
90 /// // More calls may or may not return `None`. Here, they always will.
91 /// assert_eq!(None, iter.next());
92 /// assert_eq!(None, iter.next());
95 #[stable(feature = "rust1", since = "1.0.0")]
96 fn next(&mut self) -> Option<Self::Item>;
98 /// Returns the bounds on the remaining length of the iterator.
100 /// Specifically, `size_hint()` returns a tuple where the first element
101 /// is the lower bound, and the second element is the upper bound.
103 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
104 /// A [`None`] here means that either there is no known upper bound, or the
105 /// upper bound is larger than [`usize`].
107 /// # Implementation notes
109 /// It is not enforced that an iterator implementation yields the declared
110 /// number of elements. A buggy iterator may yield less than the lower bound
111 /// or more than the upper bound of elements.
113 /// `size_hint()` is primarily intended to be used for optimizations such as
114 /// reserving space for the elements of the iterator, but must not be
115 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
116 /// implementation of `size_hint()` should not lead to memory safety
119 /// That said, the implementation should provide a correct estimation,
120 /// because otherwise it would be a violation of the trait's protocol.
122 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
125 /// [`usize`]: type@usize
132 /// let a = [1, 2, 3];
133 /// let iter = a.iter();
135 /// assert_eq!((3, Some(3)), iter.size_hint());
138 /// A more complex example:
141 /// // The even numbers in the range of zero to nine.
142 /// let iter = (0..10).filter(|x| x % 2 == 0);
144 /// // We might iterate from zero to ten times. Knowing that it's five
145 /// // exactly wouldn't be possible without executing filter().
146 /// assert_eq!((0, Some(10)), iter.size_hint());
148 /// // Let's add five more numbers with chain()
149 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
151 /// // now both bounds are increased by five
152 /// assert_eq!((5, Some(15)), iter.size_hint());
155 /// Returning `None` for an upper bound:
158 /// // an infinite iterator has no upper bound
159 /// // and the maximum possible lower bound
162 /// assert_eq!((usize::MAX, None), iter.size_hint());
165 #[stable(feature = "rust1", since = "1.0.0")]
166 fn size_hint(&self) -> (usize, Option<usize>) {
170 /// Consumes the iterator, counting the number of iterations and returning it.
172 /// This method will call [`next`] repeatedly until [`None`] is encountered,
173 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
174 /// called at least once even if the iterator does not have any elements.
176 /// [`next`]: Iterator::next
178 /// # Overflow Behavior
180 /// The method does no guarding against overflows, so counting elements of
181 /// an iterator with more than [`usize::MAX`] elements either produces the
182 /// wrong result or panics. If debug assertions are enabled, a panic is
187 /// This function might panic if the iterator has more than [`usize::MAX`]
195 /// let a = [1, 2, 3];
196 /// assert_eq!(a.iter().count(), 3);
198 /// let a = [1, 2, 3, 4, 5];
199 /// assert_eq!(a.iter().count(), 5);
202 #[stable(feature = "rust1", since = "1.0.0")]
203 fn count(self) -> usize
209 #[rustc_inherit_overflow_checks]
210 |count, _| count + 1,
214 /// Consumes the iterator, returning the last element.
216 /// This method will evaluate the iterator until it returns [`None`]. While
217 /// doing so, it keeps track of the current element. After [`None`] is
218 /// returned, `last()` will then return the last element it saw.
225 /// let a = [1, 2, 3];
226 /// assert_eq!(a.iter().last(), Some(&3));
228 /// let a = [1, 2, 3, 4, 5];
229 /// assert_eq!(a.iter().last(), Some(&5));
232 #[stable(feature = "rust1", since = "1.0.0")]
233 fn last(self) -> Option<Self::Item>
238 fn some<T>(_: Option<T>, x: T) -> Option<T> {
242 self.fold(None, some)
245 /// Advances the iterator by `n` elements.
247 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
248 /// times until [`None`] is encountered.
250 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
251 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
252 /// of elements the iterator is advanced by before running out of elements (i.e. the
253 /// length of the iterator). Note that `k` is always less than `n`.
255 /// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
257 /// [`next`]: Iterator::next
264 /// #![feature(iter_advance_by)]
266 /// let a = [1, 2, 3, 4];
267 /// let mut iter = a.iter();
269 /// assert_eq!(iter.advance_by(2), Ok(()));
270 /// assert_eq!(iter.next(), Some(&3));
271 /// assert_eq!(iter.advance_by(0), Ok(()));
272 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
275 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
276 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
278 self.next().ok_or(i)?;
283 /// Returns the `n`th element of the iterator.
285 /// Like most indexing operations, the count starts from zero, so `nth(0)`
286 /// returns the first value, `nth(1)` the second, and so on.
288 /// Note that all preceding elements, as well as the returned element, will be
289 /// consumed from the iterator. That means that the preceding elements will be
290 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
291 /// will return different elements.
293 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
301 /// let a = [1, 2, 3];
302 /// assert_eq!(a.iter().nth(1), Some(&2));
305 /// Calling `nth()` multiple times doesn't rewind the iterator:
308 /// let a = [1, 2, 3];
310 /// let mut iter = a.iter();
312 /// assert_eq!(iter.nth(1), Some(&2));
313 /// assert_eq!(iter.nth(1), None);
316 /// Returning `None` if there are less than `n + 1` elements:
319 /// let a = [1, 2, 3];
320 /// assert_eq!(a.iter().nth(10), None);
323 #[stable(feature = "rust1", since = "1.0.0")]
324 fn nth(&mut self, n: usize) -> Option<Self::Item> {
325 self.advance_by(n).ok()?;
329 /// Creates an iterator starting at the same point, but stepping by
330 /// the given amount at each iteration.
332 /// Note 1: The first element of the iterator will always be returned,
333 /// regardless of the step given.
335 /// Note 2: The time at which ignored elements are pulled is not fixed.
336 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
337 /// but is also free to behave like the sequence
338 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
339 /// Which way is used may change for some iterators for performance reasons.
340 /// The second way will advance the iterator earlier and may consume more items.
342 /// `advance_n_and_return_first` is the equivalent of:
344 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
348 /// let next = iter.next();
349 /// if total_step > 1 {
350 /// iter.nth(total_step-2);
358 /// The method will panic if the given step is `0`.
365 /// let a = [0, 1, 2, 3, 4, 5];
366 /// let mut iter = a.iter().step_by(2);
368 /// assert_eq!(iter.next(), Some(&0));
369 /// assert_eq!(iter.next(), Some(&2));
370 /// assert_eq!(iter.next(), Some(&4));
371 /// assert_eq!(iter.next(), None);
374 #[stable(feature = "iterator_step_by", since = "1.28.0")]
375 fn step_by(self, step: usize) -> StepBy<Self>
379 StepBy::new(self, step)
382 /// Takes two iterators and creates a new iterator over both in sequence.
384 /// `chain()` will return a new iterator which will first iterate over
385 /// values from the first iterator and then over values from the second
388 /// In other words, it links two iterators together, in a chain. 🔗
390 /// [`once`] is commonly used to adapt a single value into a chain of
391 /// other kinds of iteration.
398 /// let a1 = [1, 2, 3];
399 /// let a2 = [4, 5, 6];
401 /// let mut iter = a1.iter().chain(a2.iter());
403 /// assert_eq!(iter.next(), Some(&1));
404 /// assert_eq!(iter.next(), Some(&2));
405 /// assert_eq!(iter.next(), Some(&3));
406 /// assert_eq!(iter.next(), Some(&4));
407 /// assert_eq!(iter.next(), Some(&5));
408 /// assert_eq!(iter.next(), Some(&6));
409 /// assert_eq!(iter.next(), None);
412 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
413 /// anything that can be converted into an [`Iterator`], not just an
414 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
415 /// [`IntoIterator`], and so can be passed to `chain()` directly:
418 /// let s1 = &[1, 2, 3];
419 /// let s2 = &[4, 5, 6];
421 /// let mut iter = s1.iter().chain(s2);
423 /// assert_eq!(iter.next(), Some(&1));
424 /// assert_eq!(iter.next(), Some(&2));
425 /// assert_eq!(iter.next(), Some(&3));
426 /// assert_eq!(iter.next(), Some(&4));
427 /// assert_eq!(iter.next(), Some(&5));
428 /// assert_eq!(iter.next(), Some(&6));
429 /// assert_eq!(iter.next(), None);
432 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
436 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
437 /// use std::os::windows::ffi::OsStrExt;
438 /// s.encode_wide().chain(std::iter::once(0)).collect()
442 /// [`once`]: crate::iter::once
443 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
445 #[stable(feature = "rust1", since = "1.0.0")]
446 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
449 U: IntoIterator<Item = Self::Item>,
451 Chain::new(self, other.into_iter())
454 /// 'Zips up' two iterators into a single iterator of pairs.
456 /// `zip()` returns a new iterator that will iterate over two other
457 /// iterators, returning a tuple where the first element comes from the
458 /// first iterator, and the second element comes from the second iterator.
460 /// In other words, it zips two iterators together, into a single one.
462 /// If either iterator returns [`None`], [`next`] from the zipped iterator
463 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
464 /// short-circuit and `next` will not be called on the second iterator.
471 /// let a1 = [1, 2, 3];
472 /// let a2 = [4, 5, 6];
474 /// let mut iter = a1.iter().zip(a2.iter());
476 /// assert_eq!(iter.next(), Some((&1, &4)));
477 /// assert_eq!(iter.next(), Some((&2, &5)));
478 /// assert_eq!(iter.next(), Some((&3, &6)));
479 /// assert_eq!(iter.next(), None);
482 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
483 /// anything that can be converted into an [`Iterator`], not just an
484 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
485 /// [`IntoIterator`], and so can be passed to `zip()` directly:
488 /// let s1 = &[1, 2, 3];
489 /// let s2 = &[4, 5, 6];
491 /// let mut iter = s1.iter().zip(s2);
493 /// assert_eq!(iter.next(), Some((&1, &4)));
494 /// assert_eq!(iter.next(), Some((&2, &5)));
495 /// assert_eq!(iter.next(), Some((&3, &6)));
496 /// assert_eq!(iter.next(), None);
499 /// `zip()` is often used to zip an infinite iterator to a finite one.
500 /// This works because the finite iterator will eventually return [`None`],
501 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
504 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
506 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
508 /// assert_eq!((0, 'f'), enumerate[0]);
509 /// assert_eq!((0, 'f'), zipper[0]);
511 /// assert_eq!((1, 'o'), enumerate[1]);
512 /// assert_eq!((1, 'o'), zipper[1]);
514 /// assert_eq!((2, 'o'), enumerate[2]);
515 /// assert_eq!((2, 'o'), zipper[2]);
518 /// [`enumerate`]: Iterator::enumerate
519 /// [`next`]: Iterator::next
521 #[stable(feature = "rust1", since = "1.0.0")]
522 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
527 Zip::new(self, other.into_iter())
530 /// Creates a new iterator which places a copy of `separator` between adjacent
531 /// items of the original iterator.
533 /// In case `separator` does not implement [`Clone`] or needs to be
534 /// computed every time, use [`intersperse_with`].
541 /// #![feature(iter_intersperse)]
543 /// let mut a = [0, 1, 2].iter().intersperse(&100);
544 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
545 /// assert_eq!(a.next(), Some(&100)); // The separator.
546 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
547 /// assert_eq!(a.next(), Some(&100)); // The separator.
548 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
549 /// assert_eq!(a.next(), None); // The iterator is finished.
552 /// `intersperse` can be very useful to join an iterator's items using a common element:
554 /// #![feature(iter_intersperse)]
556 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
557 /// assert_eq!(hello, "Hello World !");
560 /// [`Clone`]: crate::clone::Clone
561 /// [`intersperse_with`]: Iterator::intersperse_with
563 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
564 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
569 Intersperse::new(self, separator)
572 /// Creates a new iterator which places an item generated by `separator`
573 /// between adjacent items of the original iterator.
575 /// The closure will be called exactly once each time an item is placed
576 /// between two adjacent items from the underlying iterator; specifically,
577 /// the closure is not called if the underlying iterator yields less than
578 /// two items and after the last item is yielded.
580 /// If the iterator's item implements [`Clone`], it may be easier to use
588 /// #![feature(iter_intersperse)]
590 /// #[derive(PartialEq, Debug)]
591 /// struct NotClone(usize);
593 /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
594 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
596 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
597 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
598 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
599 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
600 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
601 /// assert_eq!(it.next(), None); // The iterator is finished.
604 /// `intersperse_with` can be used in situations where the separator needs
607 /// #![feature(iter_intersperse)]
609 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
611 /// // The closure mutably borrows its context to generate an item.
612 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
613 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
615 /// let result = src.intersperse_with(separator).collect::<String>();
616 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
618 /// [`Clone`]: crate::clone::Clone
619 /// [`intersperse`]: Iterator::intersperse
621 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
622 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
625 G: FnMut() -> Self::Item,
627 IntersperseWith::new(self, separator)
630 /// Takes a closure and creates an iterator which calls that closure on each
633 /// `map()` transforms one iterator into another, by means of its argument:
634 /// something that implements [`FnMut`]. It produces a new iterator which
635 /// calls this closure on each element of the original iterator.
637 /// If you are good at thinking in types, you can think of `map()` like this:
638 /// If you have an iterator that gives you elements of some type `A`, and
639 /// you want an iterator of some other type `B`, you can use `map()`,
640 /// passing a closure that takes an `A` and returns a `B`.
642 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
643 /// lazy, it is best used when you're already working with other iterators.
644 /// If you're doing some sort of looping for a side effect, it's considered
645 /// more idiomatic to use [`for`] than `map()`.
647 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
648 /// [`FnMut`]: crate::ops::FnMut
655 /// let a = [1, 2, 3];
657 /// let mut iter = a.iter().map(|x| 2 * x);
659 /// assert_eq!(iter.next(), Some(2));
660 /// assert_eq!(iter.next(), Some(4));
661 /// assert_eq!(iter.next(), Some(6));
662 /// assert_eq!(iter.next(), None);
665 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
668 /// # #![allow(unused_must_use)]
669 /// // don't do this:
670 /// (0..5).map(|x| println!("{}", x));
672 /// // it won't even execute, as it is lazy. Rust will warn you about this.
674 /// // Instead, use for:
676 /// println!("{}", x);
680 #[stable(feature = "rust1", since = "1.0.0")]
681 fn map<B, F>(self, f: F) -> Map<Self, F>
684 F: FnMut(Self::Item) -> B,
689 /// Calls a closure on each element of an iterator.
691 /// This is equivalent to using a [`for`] loop on the iterator, although
692 /// `break` and `continue` are not possible from a closure. It's generally
693 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
694 /// when processing items at the end of longer iterator chains. In some
695 /// cases `for_each` may also be faster than a loop, because it will use
696 /// internal iteration on adaptors like `Chain`.
698 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
705 /// use std::sync::mpsc::channel;
707 /// let (tx, rx) = channel();
708 /// (0..5).map(|x| x * 2 + 1)
709 /// .for_each(move |x| tx.send(x).unwrap());
711 /// let v: Vec<_> = rx.iter().collect();
712 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
715 /// For such a small example, a `for` loop may be cleaner, but `for_each`
716 /// might be preferable to keep a functional style with longer iterators:
719 /// (0..5).flat_map(|x| x * 100 .. x * 110)
721 /// .filter(|&(i, x)| (i + x) % 3 == 0)
722 /// .for_each(|(i, x)| println!("{}:{}", i, x));
725 #[stable(feature = "iterator_for_each", since = "1.21.0")]
726 fn for_each<F>(self, f: F)
729 F: FnMut(Self::Item),
732 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
733 move |(), item| f(item)
736 self.fold((), call(f));
739 /// Creates an iterator which uses a closure to determine if an element
740 /// should be yielded.
742 /// Given an element the closure must return `true` or `false`. The returned
743 /// iterator will yield only the elements for which the closure returns
751 /// let a = [0i32, 1, 2];
753 /// let mut iter = a.iter().filter(|x| x.is_positive());
755 /// assert_eq!(iter.next(), Some(&1));
756 /// assert_eq!(iter.next(), Some(&2));
757 /// assert_eq!(iter.next(), None);
760 /// Because the closure passed to `filter()` takes a reference, and many
761 /// iterators iterate over references, this leads to a possibly confusing
762 /// situation, where the type of the closure is a double reference:
765 /// let a = [0, 1, 2];
767 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
769 /// assert_eq!(iter.next(), Some(&2));
770 /// assert_eq!(iter.next(), None);
773 /// It's common to instead use destructuring on the argument to strip away
777 /// let a = [0, 1, 2];
779 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
781 /// assert_eq!(iter.next(), Some(&2));
782 /// assert_eq!(iter.next(), None);
788 /// let a = [0, 1, 2];
790 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
792 /// assert_eq!(iter.next(), Some(&2));
793 /// assert_eq!(iter.next(), None);
798 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
800 #[stable(feature = "rust1", since = "1.0.0")]
801 fn filter<P>(self, predicate: P) -> Filter<Self, P>
804 P: FnMut(&Self::Item) -> bool,
806 Filter::new(self, predicate)
809 /// Creates an iterator that both filters and maps.
811 /// The returned iterator yields only the `value`s for which the supplied
812 /// closure returns `Some(value)`.
814 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
815 /// concise. The example below shows how a `map().filter().map()` can be
816 /// shortened to a single call to `filter_map`.
818 /// [`filter`]: Iterator::filter
819 /// [`map`]: Iterator::map
826 /// let a = ["1", "two", "NaN", "four", "5"];
828 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
830 /// assert_eq!(iter.next(), Some(1));
831 /// assert_eq!(iter.next(), Some(5));
832 /// assert_eq!(iter.next(), None);
835 /// Here's the same example, but with [`filter`] and [`map`]:
838 /// let a = ["1", "two", "NaN", "four", "5"];
839 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
840 /// assert_eq!(iter.next(), Some(1));
841 /// assert_eq!(iter.next(), Some(5));
842 /// assert_eq!(iter.next(), None);
845 #[stable(feature = "rust1", since = "1.0.0")]
846 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
849 F: FnMut(Self::Item) -> Option<B>,
851 FilterMap::new(self, f)
854 /// Creates an iterator which gives the current iteration count as well as
857 /// The iterator returned yields pairs `(i, val)`, where `i` is the
858 /// current index of iteration and `val` is the value returned by the
861 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
862 /// different sized integer, the [`zip`] function provides similar
865 /// # Overflow Behavior
867 /// The method does no guarding against overflows, so enumerating more than
868 /// [`usize::MAX`] elements either produces the wrong result or panics. If
869 /// debug assertions are enabled, a panic is guaranteed.
873 /// The returned iterator might panic if the to-be-returned index would
874 /// overflow a [`usize`].
876 /// [`usize`]: type@usize
877 /// [`zip`]: Iterator::zip
882 /// let a = ['a', 'b', 'c'];
884 /// let mut iter = a.iter().enumerate();
886 /// assert_eq!(iter.next(), Some((0, &'a')));
887 /// assert_eq!(iter.next(), Some((1, &'b')));
888 /// assert_eq!(iter.next(), Some((2, &'c')));
889 /// assert_eq!(iter.next(), None);
892 #[stable(feature = "rust1", since = "1.0.0")]
893 fn enumerate(self) -> Enumerate<Self>
900 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
901 /// to look at the next element of the iterator without consuming it. See
902 /// their documentation for more information.
904 /// Note that the underlying iterator is still advanced when [`peek`] or
905 /// [`peek_mut`] are called for the first time: In order to retrieve the
906 /// next element, [`next`] is called on the underlying iterator, hence any
907 /// side effects (i.e. anything other than fetching the next value) of
908 /// the [`next`] method will occur.
916 /// let xs = [1, 2, 3];
918 /// let mut iter = xs.iter().peekable();
920 /// // peek() lets us see into the future
921 /// assert_eq!(iter.peek(), Some(&&1));
922 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), Some(&2));
926 /// // we can peek() multiple times, the iterator won't advance
927 /// assert_eq!(iter.peek(), Some(&&3));
928 /// assert_eq!(iter.peek(), Some(&&3));
930 /// assert_eq!(iter.next(), Some(&3));
932 /// // after the iterator is finished, so is peek()
933 /// assert_eq!(iter.peek(), None);
934 /// assert_eq!(iter.next(), None);
937 /// Using [`peek_mut`] to mutate the next item without advancing the
941 /// let xs = [1, 2, 3];
943 /// let mut iter = xs.iter().peekable();
945 /// // `peek_mut()` lets us see into the future
946 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
947 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
948 /// assert_eq!(iter.next(), Some(&1));
950 /// if let Some(mut p) = iter.peek_mut() {
951 /// assert_eq!(*p, &2);
952 /// // put a value into the iterator
956 /// // The value reappears as the iterator continues
957 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
959 /// [`peek`]: Peekable::peek
960 /// [`peek_mut`]: Peekable::peek_mut
961 /// [`next`]: Iterator::next
963 #[stable(feature = "rust1", since = "1.0.0")]
964 fn peekable(self) -> Peekable<Self>
971 /// Creates an iterator that [`skip`]s elements based on a predicate.
973 /// [`skip`]: Iterator::skip
975 /// `skip_while()` takes a closure as an argument. It will call this
976 /// closure on each element of the iterator, and ignore elements
977 /// until it returns `false`.
979 /// After `false` is returned, `skip_while()`'s job is over, and the
980 /// rest of the elements are yielded.
987 /// let a = [-1i32, 0, 1];
989 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
991 /// assert_eq!(iter.next(), Some(&0));
992 /// assert_eq!(iter.next(), Some(&1));
993 /// assert_eq!(iter.next(), None);
996 /// Because the closure passed to `skip_while()` takes a reference, and many
997 /// iterators iterate over references, this leads to a possibly confusing
998 /// situation, where the type of the closure argument is a double reference:
1001 /// let a = [-1, 0, 1];
1003 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1005 /// assert_eq!(iter.next(), Some(&0));
1006 /// assert_eq!(iter.next(), Some(&1));
1007 /// assert_eq!(iter.next(), None);
1010 /// Stopping after an initial `false`:
1013 /// let a = [-1, 0, 1, -2];
1015 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1017 /// assert_eq!(iter.next(), Some(&0));
1018 /// assert_eq!(iter.next(), Some(&1));
1020 /// // while this would have been false, since we already got a false,
1021 /// // skip_while() isn't used any more
1022 /// assert_eq!(iter.next(), Some(&-2));
1024 /// assert_eq!(iter.next(), None);
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1031 P: FnMut(&Self::Item) -> bool,
1033 SkipWhile::new(self, predicate)
1036 /// Creates an iterator that yields elements based on a predicate.
1038 /// `take_while()` takes a closure as an argument. It will call this
1039 /// closure on each element of the iterator, and yield elements
1040 /// while it returns `true`.
1042 /// After `false` is returned, `take_while()`'s job is over, and the
1043 /// rest of the elements are ignored.
1050 /// let a = [-1i32, 0, 1];
1052 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1054 /// assert_eq!(iter.next(), Some(&-1));
1055 /// assert_eq!(iter.next(), None);
1058 /// Because the closure passed to `take_while()` takes a reference, and many
1059 /// iterators iterate over references, this leads to a possibly confusing
1060 /// situation, where the type of the closure is a double reference:
1063 /// let a = [-1, 0, 1];
1065 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1067 /// assert_eq!(iter.next(), Some(&-1));
1068 /// assert_eq!(iter.next(), None);
1071 /// Stopping after an initial `false`:
1074 /// let a = [-1, 0, 1, -2];
1076 /// let mut iter = a.iter().take_while(|x| **x < 0);
1078 /// assert_eq!(iter.next(), Some(&-1));
1080 /// // We have more elements that are less than zero, but since we already
1081 /// // got a false, take_while() isn't used any more
1082 /// assert_eq!(iter.next(), None);
1085 /// Because `take_while()` needs to look at the value in order to see if it
1086 /// should be included or not, consuming iterators will see that it is
1090 /// let a = [1, 2, 3, 4];
1091 /// let mut iter = a.iter();
1093 /// let result: Vec<i32> = iter.by_ref()
1094 /// .take_while(|n| **n != 3)
1098 /// assert_eq!(result, &[1, 2]);
1100 /// let result: Vec<i32> = iter.cloned().collect();
1102 /// assert_eq!(result, &[4]);
1105 /// The `3` is no longer there, because it was consumed in order to see if
1106 /// the iteration should stop, but wasn't placed back into the iterator.
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1112 P: FnMut(&Self::Item) -> bool,
1114 TakeWhile::new(self, predicate)
1117 /// Creates an iterator that both yields elements based on a predicate and maps.
1119 /// `map_while()` takes a closure as an argument. It will call this
1120 /// closure on each element of the iterator, and yield elements
1121 /// while it returns [`Some(_)`][`Some`].
1128 /// #![feature(iter_map_while)]
1129 /// let a = [-1i32, 4, 0, 1];
1131 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1133 /// assert_eq!(iter.next(), Some(-16));
1134 /// assert_eq!(iter.next(), Some(4));
1135 /// assert_eq!(iter.next(), None);
1138 /// Here's the same example, but with [`take_while`] and [`map`]:
1140 /// [`take_while`]: Iterator::take_while
1141 /// [`map`]: Iterator::map
1144 /// let a = [-1i32, 4, 0, 1];
1146 /// let mut iter = a.iter()
1147 /// .map(|x| 16i32.checked_div(*x))
1148 /// .take_while(|x| x.is_some())
1149 /// .map(|x| x.unwrap());
1151 /// assert_eq!(iter.next(), Some(-16));
1152 /// assert_eq!(iter.next(), Some(4));
1153 /// assert_eq!(iter.next(), None);
1156 /// Stopping after an initial [`None`]:
1159 /// #![feature(iter_map_while)]
1160 /// use std::convert::TryFrom;
1162 /// let a = [0, 1, 2, -3, 4, 5, -6];
1164 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1165 /// let vec = iter.collect::<Vec<_>>();
1167 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1168 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1169 /// assert_eq!(vec, vec![0, 1, 2]);
1172 /// Because `map_while()` needs to look at the value in order to see if it
1173 /// should be included or not, consuming iterators will see that it is
1177 /// #![feature(iter_map_while)]
1178 /// use std::convert::TryFrom;
1180 /// let a = [1, 2, -3, 4];
1181 /// let mut iter = a.iter();
1183 /// let result: Vec<u32> = iter.by_ref()
1184 /// .map_while(|n| u32::try_from(*n).ok())
1187 /// assert_eq!(result, &[1, 2]);
1189 /// let result: Vec<i32> = iter.cloned().collect();
1191 /// assert_eq!(result, &[4]);
1194 /// The `-3` is no longer there, because it was consumed in order to see if
1195 /// the iteration should stop, but wasn't placed back into the iterator.
1197 /// Note that unlike [`take_while`] this iterator is **not** fused.
1198 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1199 /// If you need fused iterator, use [`fuse`].
1201 /// [`fuse`]: Iterator::fuse
1203 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1204 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1207 P: FnMut(Self::Item) -> Option<B>,
1209 MapWhile::new(self, predicate)
1212 /// Creates an iterator that skips the first `n` elements.
1214 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1215 /// iterator is reached (whichever happens first). After that, all the remaining
1216 /// elements are yielded. In particular, if the original iterator is too short,
1217 /// then the returned iterator is empty.
1219 /// Rather than overriding this method directly, instead override the `nth` method.
1226 /// let a = [1, 2, 3];
1228 /// let mut iter = a.iter().skip(2);
1230 /// assert_eq!(iter.next(), Some(&3));
1231 /// assert_eq!(iter.next(), None);
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 fn skip(self, n: usize) -> Skip<Self>
1242 /// Creates an iterator that yields the first `n` elements, or fewer
1243 /// if the underlying iterator ends sooner.
1245 /// `take(n)` yields elements until `n` elements are yielded or the end of
1246 /// the iterator is reached (whichever happens first).
1247 /// The returned iterator is a prefix of length `n` if the original iterator
1248 /// contains at least `n` elements, otherwise it contains all of the
1249 /// (fewer than `n`) elements of the original iterator.
1256 /// let a = [1, 2, 3];
1258 /// let mut iter = a.iter().take(2);
1260 /// assert_eq!(iter.next(), Some(&1));
1261 /// assert_eq!(iter.next(), Some(&2));
1262 /// assert_eq!(iter.next(), None);
1265 /// `take()` is often used with an infinite iterator, to make it finite:
1268 /// let mut iter = (0..).take(3);
1270 /// assert_eq!(iter.next(), Some(0));
1271 /// assert_eq!(iter.next(), Some(1));
1272 /// assert_eq!(iter.next(), Some(2));
1273 /// assert_eq!(iter.next(), None);
1276 /// If less than `n` elements are available,
1277 /// `take` will limit itself to the size of the underlying iterator:
1280 /// let v = vec![1, 2];
1281 /// let mut iter = v.into_iter().take(5);
1282 /// assert_eq!(iter.next(), Some(1));
1283 /// assert_eq!(iter.next(), Some(2));
1284 /// assert_eq!(iter.next(), None);
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 fn take(self, n: usize) -> Take<Self>
1295 /// An iterator adaptor similar to [`fold`] that holds internal state and
1296 /// produces a new iterator.
1298 /// [`fold`]: Iterator::fold
1300 /// `scan()` takes two arguments: an initial value which seeds the internal
1301 /// state, and a closure with two arguments, the first being a mutable
1302 /// reference to the internal state and the second an iterator element.
1303 /// The closure can assign to the internal state to share state between
1306 /// On iteration, the closure will be applied to each element of the
1307 /// iterator and the return value from the closure, an [`Option`], is
1308 /// yielded by the iterator.
1315 /// let a = [1, 2, 3];
1317 /// let mut iter = a.iter().scan(1, |state, &x| {
1318 /// // each iteration, we'll multiply the state by the element
1319 /// *state = *state * x;
1321 /// // then, we'll yield the negation of the state
1325 /// assert_eq!(iter.next(), Some(-1));
1326 /// assert_eq!(iter.next(), Some(-2));
1327 /// assert_eq!(iter.next(), Some(-6));
1328 /// assert_eq!(iter.next(), None);
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1335 F: FnMut(&mut St, Self::Item) -> Option<B>,
1337 Scan::new(self, initial_state, f)
1340 /// Creates an iterator that works like map, but flattens nested structure.
1342 /// The [`map`] adapter is very useful, but only when the closure
1343 /// argument produces values. If it produces an iterator instead, there's
1344 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1347 /// You can think of `flat_map(f)` as the semantic equivalent
1348 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1350 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1351 /// one item for each element, and `flat_map()`'s closure returns an
1352 /// iterator for each element.
1354 /// [`map`]: Iterator::map
1355 /// [`flatten`]: Iterator::flatten
1362 /// let words = ["alpha", "beta", "gamma"];
1364 /// // chars() returns an iterator
1365 /// let merged: String = words.iter()
1366 /// .flat_map(|s| s.chars())
1368 /// assert_eq!(merged, "alphabetagamma");
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1376 F: FnMut(Self::Item) -> U,
1378 FlatMap::new(self, f)
1381 /// Creates an iterator that flattens nested structure.
1383 /// This is useful when you have an iterator of iterators or an iterator of
1384 /// things that can be turned into iterators and you want to remove one
1385 /// level of indirection.
1392 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1393 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1394 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1397 /// Mapping and then flattening:
1400 /// let words = ["alpha", "beta", "gamma"];
1402 /// // chars() returns an iterator
1403 /// let merged: String = words.iter()
1404 /// .map(|s| s.chars())
1407 /// assert_eq!(merged, "alphabetagamma");
1410 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1411 /// in this case since it conveys intent more clearly:
1414 /// let words = ["alpha", "beta", "gamma"];
1416 /// // chars() returns an iterator
1417 /// let merged: String = words.iter()
1418 /// .flat_map(|s| s.chars())
1420 /// assert_eq!(merged, "alphabetagamma");
1423 /// Flattening only removes one level of nesting at a time:
1426 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1428 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1429 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1431 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1432 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1435 /// Here we see that `flatten()` does not perform a "deep" flatten.
1436 /// Instead, only one level of nesting is removed. That is, if you
1437 /// `flatten()` a three-dimensional array, the result will be
1438 /// two-dimensional and not one-dimensional. To get a one-dimensional
1439 /// structure, you have to `flatten()` again.
1441 /// [`flat_map()`]: Iterator::flat_map
1443 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1444 fn flatten(self) -> Flatten<Self>
1447 Self::Item: IntoIterator,
1452 /// Creates an iterator which ends after the first [`None`].
1454 /// After an iterator returns [`None`], future calls may or may not yield
1455 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1456 /// [`None`] is given, it will always return [`None`] forever.
1458 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1459 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1460 /// if the [`FusedIterator`] trait is improperly implemented.
1462 /// [`Some(T)`]: Some
1463 /// [`FusedIterator`]: crate::iter::FusedIterator
1470 /// // an iterator which alternates between Some and None
1471 /// struct Alternate {
1475 /// impl Iterator for Alternate {
1476 /// type Item = i32;
1478 /// fn next(&mut self) -> Option<i32> {
1479 /// let val = self.state;
1480 /// self.state = self.state + 1;
1482 /// // if it's even, Some(i32), else None
1483 /// if val % 2 == 0 {
1491 /// let mut iter = Alternate { state: 0 };
1493 /// // we can see our iterator going back and forth
1494 /// assert_eq!(iter.next(), Some(0));
1495 /// assert_eq!(iter.next(), None);
1496 /// assert_eq!(iter.next(), Some(2));
1497 /// assert_eq!(iter.next(), None);
1499 /// // however, once we fuse it...
1500 /// let mut iter = iter.fuse();
1502 /// assert_eq!(iter.next(), Some(4));
1503 /// assert_eq!(iter.next(), None);
1505 /// // it will always return `None` after the first time.
1506 /// assert_eq!(iter.next(), None);
1507 /// assert_eq!(iter.next(), None);
1508 /// assert_eq!(iter.next(), None);
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 fn fuse(self) -> Fuse<Self>
1519 /// Does something with each element of an iterator, passing the value on.
1521 /// When using iterators, you'll often chain several of them together.
1522 /// While working on such code, you might want to check out what's
1523 /// happening at various parts in the pipeline. To do that, insert
1524 /// a call to `inspect()`.
1526 /// It's more common for `inspect()` to be used as a debugging tool than to
1527 /// exist in your final code, but applications may find it useful in certain
1528 /// situations when errors need to be logged before being discarded.
1535 /// let a = [1, 4, 2, 3];
1537 /// // this iterator sequence is complex.
1538 /// let sum = a.iter()
1540 /// .filter(|x| x % 2 == 0)
1541 /// .fold(0, |sum, i| sum + i);
1543 /// println!("{}", sum);
1545 /// // let's add some inspect() calls to investigate what's happening
1546 /// let sum = a.iter()
1548 /// .inspect(|x| println!("about to filter: {}", x))
1549 /// .filter(|x| x % 2 == 0)
1550 /// .inspect(|x| println!("made it through filter: {}", x))
1551 /// .fold(0, |sum, i| sum + i);
1553 /// println!("{}", sum);
1556 /// This will print:
1560 /// about to filter: 1
1561 /// about to filter: 4
1562 /// made it through filter: 4
1563 /// about to filter: 2
1564 /// made it through filter: 2
1565 /// about to filter: 3
1569 /// Logging errors before discarding them:
1572 /// let lines = ["1", "2", "a"];
1574 /// let sum: i32 = lines
1576 /// .map(|line| line.parse::<i32>())
1577 /// .inspect(|num| {
1578 /// if let Err(ref e) = *num {
1579 /// println!("Parsing error: {}", e);
1582 /// .filter_map(Result::ok)
1585 /// println!("Sum: {}", sum);
1588 /// This will print:
1591 /// Parsing error: invalid digit found in string
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1599 F: FnMut(&Self::Item),
1601 Inspect::new(self, f)
1604 /// Borrows an iterator, rather than consuming it.
1606 /// This is useful to allow applying iterator adaptors while still
1607 /// retaining ownership of the original iterator.
1614 /// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
1616 /// // Take the first two words.
1617 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1618 /// assert_eq!(hello_world, vec!["hello", "world"]);
1620 /// // Collect the rest of the words.
1621 /// // We can only do this because we used `by_ref` earlier.
1622 /// let of_rust: Vec<_> = words.collect();
1623 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 fn by_ref(&mut self) -> &mut Self
1633 /// Transforms an iterator into a collection.
1635 /// `collect()` can take anything iterable, and turn it into a relevant
1636 /// collection. This is one of the more powerful methods in the standard
1637 /// library, used in a variety of contexts.
1639 /// The most basic pattern in which `collect()` is used is to turn one
1640 /// collection into another. You take a collection, call [`iter`] on it,
1641 /// do a bunch of transformations, and then `collect()` at the end.
1643 /// `collect()` can also create instances of types that are not typical
1644 /// collections. For example, a [`String`] can be built from [`char`]s,
1645 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1646 /// into `Result<Collection<T>, E>`. See the examples below for more.
1648 /// Because `collect()` is so general, it can cause problems with type
1649 /// inference. As such, `collect()` is one of the few times you'll see
1650 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1651 /// helps the inference algorithm understand specifically which collection
1652 /// you're trying to collect into.
1659 /// let a = [1, 2, 3];
1661 /// let doubled: Vec<i32> = a.iter()
1662 /// .map(|&x| x * 2)
1665 /// assert_eq!(vec![2, 4, 6], doubled);
1668 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1669 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1671 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1674 /// use std::collections::VecDeque;
1676 /// let a = [1, 2, 3];
1678 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1680 /// assert_eq!(2, doubled[0]);
1681 /// assert_eq!(4, doubled[1]);
1682 /// assert_eq!(6, doubled[2]);
1685 /// Using the 'turbofish' instead of annotating `doubled`:
1688 /// let a = [1, 2, 3];
1690 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1692 /// assert_eq!(vec![2, 4, 6], doubled);
1695 /// Because `collect()` only cares about what you're collecting into, you can
1696 /// still use a partial type hint, `_`, with the turbofish:
1699 /// let a = [1, 2, 3];
1701 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1703 /// assert_eq!(vec![2, 4, 6], doubled);
1706 /// Using `collect()` to make a [`String`]:
1709 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1711 /// let hello: String = chars.iter()
1712 /// .map(|&x| x as u8)
1713 /// .map(|x| (x + 1) as char)
1716 /// assert_eq!("hello", hello);
1719 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1720 /// see if any of them failed:
1723 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1725 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1727 /// // gives us the first error
1728 /// assert_eq!(Err("nope"), result);
1730 /// let results = [Ok(1), Ok(3)];
1732 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1734 /// // gives us the list of answers
1735 /// assert_eq!(Ok(vec![1, 3]), result);
1738 /// [`iter`]: Iterator::next
1739 /// [`String`]: ../../std/string/struct.String.html
1740 /// [`char`]: type@char
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1744 fn collect<B: FromIterator<Self::Item>>(self) -> B
1748 FromIterator::from_iter(self)
1751 /// Consumes an iterator, creating two collections from it.
1753 /// The predicate passed to `partition()` can return `true`, or `false`.
1754 /// `partition()` returns a pair, all of the elements for which it returned
1755 /// `true`, and all of the elements for which it returned `false`.
1757 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1759 /// [`is_partitioned()`]: Iterator::is_partitioned
1760 /// [`partition_in_place()`]: Iterator::partition_in_place
1767 /// let a = [1, 2, 3];
1769 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1771 /// .partition(|&n| n % 2 == 0);
1773 /// assert_eq!(even, vec![2]);
1774 /// assert_eq!(odd, vec![1, 3]);
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 fn partition<B, F>(self, f: F) -> (B, B)
1780 B: Default + Extend<Self::Item>,
1781 F: FnMut(&Self::Item) -> bool,
1784 fn extend<'a, T, B: Extend<T>>(
1785 mut f: impl FnMut(&T) -> bool + 'a,
1788 ) -> impl FnMut((), T) + 'a {
1793 right.extend_one(x);
1798 let mut left: B = Default::default();
1799 let mut right: B = Default::default();
1801 self.fold((), extend(f, &mut left, &mut right));
1806 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1807 /// such that all those that return `true` precede all those that return `false`.
1808 /// Returns the number of `true` elements found.
1810 /// The relative order of partitioned items is not maintained.
1812 /// # Current implementation
1813 /// Current algorithms tries finding the first element for which the predicate evaluates
1814 /// to false, and the last element for which it evaluates to true and repeatedly swaps them.
1816 /// Time Complexity: *O*(*N*)
1818 /// See also [`is_partitioned()`] and [`partition()`].
1820 /// [`is_partitioned()`]: Iterator::is_partitioned
1821 /// [`partition()`]: Iterator::partition
1826 /// #![feature(iter_partition_in_place)]
1828 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1830 /// // Partition in-place between evens and odds
1831 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1833 /// assert_eq!(i, 3);
1834 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1835 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1837 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1838 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1840 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1841 P: FnMut(&T) -> bool,
1843 // FIXME: should we worry about the count overflowing? The only way to have more than
1844 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1846 // These closure "factory" functions exist to avoid genericity in `Self`.
1850 predicate: &'a mut impl FnMut(&T) -> bool,
1851 true_count: &'a mut usize,
1852 ) -> impl FnMut(&&mut T) -> bool + 'a {
1854 let p = predicate(&**x);
1855 *true_count += p as usize;
1861 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1862 move |x| predicate(&**x)
1865 // Repeatedly find the first `false` and swap it with the last `true`.
1866 let mut true_count = 0;
1867 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1868 if let Some(tail) = self.rfind(is_true(predicate)) {
1869 crate::mem::swap(head, tail);
1878 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1879 /// such that all those that return `true` precede all those that return `false`.
1881 /// See also [`partition()`] and [`partition_in_place()`].
1883 /// [`partition()`]: Iterator::partition
1884 /// [`partition_in_place()`]: Iterator::partition_in_place
1889 /// #![feature(iter_is_partitioned)]
1891 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1892 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1894 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1895 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1898 P: FnMut(Self::Item) -> bool,
1900 // Either all items test `true`, or the first clause stops at `false`
1901 // and we check that there are no more `true` items after that.
1902 self.all(&mut predicate) || !self.any(predicate)
1905 /// An iterator method that applies a function as long as it returns
1906 /// successfully, producing a single, final value.
1908 /// `try_fold()` takes two arguments: an initial value, and a closure with
1909 /// two arguments: an 'accumulator', and an element. The closure either
1910 /// returns successfully, with the value that the accumulator should have
1911 /// for the next iteration, or it returns failure, with an error value that
1912 /// is propagated back to the caller immediately (short-circuiting).
1914 /// The initial value is the value the accumulator will have on the first
1915 /// call. If applying the closure succeeded against every element of the
1916 /// iterator, `try_fold()` returns the final accumulator as success.
1918 /// Folding is useful whenever you have a collection of something, and want
1919 /// to produce a single value from it.
1921 /// # Note to Implementors
1923 /// Several of the other (forward) methods have default implementations in
1924 /// terms of this one, so try to implement this explicitly if it can
1925 /// do something better than the default `for` loop implementation.
1927 /// In particular, try to have this call `try_fold()` on the internal parts
1928 /// from which this iterator is composed. If multiple calls are needed,
1929 /// the `?` operator may be convenient for chaining the accumulator value
1930 /// along, but beware any invariants that need to be upheld before those
1931 /// early returns. This is a `&mut self` method, so iteration needs to be
1932 /// resumable after hitting an error here.
1939 /// let a = [1, 2, 3];
1941 /// // the checked sum of all of the elements of the array
1942 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1944 /// assert_eq!(sum, Some(6));
1947 /// Short-circuiting:
1950 /// let a = [10, 20, 30, 100, 40, 50];
1951 /// let mut it = a.iter();
1953 /// // This sum overflows when adding the 100 element
1954 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1955 /// assert_eq!(sum, None);
1957 /// // Because it short-circuited, the remaining elements are still
1958 /// // available through the iterator.
1959 /// assert_eq!(it.len(), 2);
1960 /// assert_eq!(it.next(), Some(&40));
1963 /// While you cannot `break` from a closure, the [`crate::ops::ControlFlow`]
1964 /// type allows a similar idea:
1967 /// use std::ops::ControlFlow;
1969 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
1970 /// if let Some(next) = prev.checked_add(x) {
1971 /// ControlFlow::Continue(next)
1973 /// ControlFlow::Break(prev)
1976 /// assert_eq!(triangular, ControlFlow::Break(120));
1978 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
1979 /// if let Some(next) = prev.checked_add(x) {
1980 /// ControlFlow::Continue(next)
1982 /// ControlFlow::Break(prev)
1985 /// assert_eq!(triangular, ControlFlow::Continue(435));
1988 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1989 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1992 F: FnMut(B, Self::Item) -> R,
1995 let mut accum = init;
1996 while let Some(x) = self.next() {
1997 accum = f(accum, x)?;
2002 /// An iterator method that applies a fallible function to each item in the
2003 /// iterator, stopping at the first error and returning that error.
2005 /// This can also be thought of as the fallible form of [`for_each()`]
2006 /// or as the stateless version of [`try_fold()`].
2008 /// [`for_each()`]: Iterator::for_each
2009 /// [`try_fold()`]: Iterator::try_fold
2014 /// use std::fs::rename;
2015 /// use std::io::{stdout, Write};
2016 /// use std::path::Path;
2018 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2020 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
2021 /// assert!(res.is_ok());
2023 /// let mut it = data.iter().cloned();
2024 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2025 /// assert!(res.is_err());
2026 /// // It short-circuited, so the remaining items are still in the iterator:
2027 /// assert_eq!(it.next(), Some("stale_bread.json"));
2030 /// The [`crate::ops::ControlFlow`] type can be used with this method for the
2031 /// situations in which you'd use `break` and `continue` in a normal loop:
2034 /// use std::ops::ControlFlow;
2036 /// let r = (2..100).try_for_each(|x| {
2037 /// if 323 % x == 0 {
2038 /// return ControlFlow::Break(x)
2041 /// ControlFlow::Continue(())
2043 /// assert_eq!(r, ControlFlow::Break(17));
2046 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2047 fn try_for_each<F, R>(&mut self, f: F) -> R
2050 F: FnMut(Self::Item) -> R,
2051 R: Try<Output = ()>,
2054 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2058 self.try_fold((), call(f))
2061 /// Folds every element into an accumulator by applying an operation,
2062 /// returning the final result.
2064 /// `fold()` takes two arguments: an initial value, and a closure with two
2065 /// arguments: an 'accumulator', and an element. The closure returns the value that
2066 /// the accumulator should have for the next iteration.
2068 /// The initial value is the value the accumulator will have on the first
2071 /// After applying this closure to every element of the iterator, `fold()`
2072 /// returns the accumulator.
2074 /// This operation is sometimes called 'reduce' or 'inject'.
2076 /// Folding is useful whenever you have a collection of something, and want
2077 /// to produce a single value from it.
2079 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2080 /// may not terminate for infinite iterators, even on traits for which a
2081 /// result is determinable in finite time.
2083 /// Note: [`reduce()`] can be used to use the first element as the initial
2084 /// value, if the accumulator type and item type is the same.
2086 /// # Note to Implementors
2088 /// Several of the other (forward) methods have default implementations in
2089 /// terms of this one, so try to implement this explicitly if it can
2090 /// do something better than the default `for` loop implementation.
2092 /// In particular, try to have this call `fold()` on the internal parts
2093 /// from which this iterator is composed.
2100 /// let a = [1, 2, 3];
2102 /// // the sum of all of the elements of the array
2103 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2105 /// assert_eq!(sum, 6);
2108 /// Let's walk through each step of the iteration here:
2110 /// | element | acc | x | result |
2111 /// |---------|-----|---|--------|
2113 /// | 1 | 0 | 1 | 1 |
2114 /// | 2 | 1 | 2 | 3 |
2115 /// | 3 | 3 | 3 | 6 |
2117 /// And so, our final result, `6`.
2119 /// It's common for people who haven't used iterators a lot to
2120 /// use a `for` loop with a list of things to build up a result. Those
2121 /// can be turned into `fold()`s:
2123 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2126 /// let numbers = [1, 2, 3, 4, 5];
2128 /// let mut result = 0;
2131 /// for i in &numbers {
2132 /// result = result + i;
2136 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2138 /// // they're the same
2139 /// assert_eq!(result, result2);
2142 /// [`reduce()`]: Iterator::reduce
2143 #[doc(alias = "inject")]
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2149 F: FnMut(B, Self::Item) -> B,
2151 let mut accum = init;
2152 while let Some(x) = self.next() {
2153 accum = f(accum, x);
2158 /// Reduces the elements to a single one, by repeatedly applying a reducing
2161 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2162 /// result of the reduction.
2164 /// For iterators with at least one element, this is the same as [`fold()`]
2165 /// with the first element of the iterator as the initial value, folding
2166 /// every subsequent element into it.
2168 /// [`fold()`]: Iterator::fold
2172 /// Find the maximum value:
2175 /// fn find_max<I>(iter: I) -> Option<I::Item>
2176 /// where I: Iterator,
2179 /// iter.reduce(|a, b| {
2180 /// if a >= b { a } else { b }
2183 /// let a = [10, 20, 5, -23, 0];
2184 /// let b: [u32; 0] = [];
2186 /// assert_eq!(find_max(a.iter()), Some(&20));
2187 /// assert_eq!(find_max(b.iter()), None);
2190 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2191 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2194 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2196 let first = self.next()?;
2197 Some(self.fold(first, f))
2200 /// Tests if every element of the iterator matches a predicate.
2202 /// `all()` takes a closure that returns `true` or `false`. It applies
2203 /// this closure to each element of the iterator, and if they all return
2204 /// `true`, then so does `all()`. If any of them return `false`, it
2205 /// returns `false`.
2207 /// `all()` is short-circuiting; in other words, it will stop processing
2208 /// as soon as it finds a `false`, given that no matter what else happens,
2209 /// the result will also be `false`.
2211 /// An empty iterator returns `true`.
2218 /// let a = [1, 2, 3];
2220 /// assert!(a.iter().all(|&x| x > 0));
2222 /// assert!(!a.iter().all(|&x| x > 2));
2225 /// Stopping at the first `false`:
2228 /// let a = [1, 2, 3];
2230 /// let mut iter = a.iter();
2232 /// assert!(!iter.all(|&x| x != 2));
2234 /// // we can still use `iter`, as there are more elements.
2235 /// assert_eq!(iter.next(), Some(&3));
2237 #[doc(alias = "every")]
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 fn all<F>(&mut self, f: F) -> bool
2243 F: FnMut(Self::Item) -> bool,
2246 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2248 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2251 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2254 /// Tests if any element of the iterator matches a predicate.
2256 /// `any()` takes a closure that returns `true` or `false`. It applies
2257 /// this closure to each element of the iterator, and if any of them return
2258 /// `true`, then so does `any()`. If they all return `false`, it
2259 /// returns `false`.
2261 /// `any()` is short-circuiting; in other words, it will stop processing
2262 /// as soon as it finds a `true`, given that no matter what else happens,
2263 /// the result will also be `true`.
2265 /// An empty iterator returns `false`.
2272 /// let a = [1, 2, 3];
2274 /// assert!(a.iter().any(|&x| x > 0));
2276 /// assert!(!a.iter().any(|&x| x > 5));
2279 /// Stopping at the first `true`:
2282 /// let a = [1, 2, 3];
2284 /// let mut iter = a.iter();
2286 /// assert!(iter.any(|&x| x != 2));
2288 /// // we can still use `iter`, as there are more elements.
2289 /// assert_eq!(iter.next(), Some(&2));
2292 #[stable(feature = "rust1", since = "1.0.0")]
2293 fn any<F>(&mut self, f: F) -> bool
2296 F: FnMut(Self::Item) -> bool,
2299 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2301 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2305 self.try_fold((), check(f)) == ControlFlow::BREAK
2308 /// Searches for an element of an iterator that satisfies a predicate.
2310 /// `find()` takes a closure that returns `true` or `false`. It applies
2311 /// this closure to each element of the iterator, and if any of them return
2312 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2313 /// `false`, it returns [`None`].
2315 /// `find()` is short-circuiting; in other words, it will stop processing
2316 /// as soon as the closure returns `true`.
2318 /// Because `find()` takes a reference, and many iterators iterate over
2319 /// references, this leads to a possibly confusing situation where the
2320 /// argument is a double reference. You can see this effect in the
2321 /// examples below, with `&&x`.
2323 /// [`Some(element)`]: Some
2330 /// let a = [1, 2, 3];
2332 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2334 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2337 /// Stopping at the first `true`:
2340 /// let a = [1, 2, 3];
2342 /// let mut iter = a.iter();
2344 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2346 /// // we can still use `iter`, as there are more elements.
2347 /// assert_eq!(iter.next(), Some(&3));
2350 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2352 #[stable(feature = "rust1", since = "1.0.0")]
2353 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2356 P: FnMut(&Self::Item) -> bool,
2359 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2361 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2365 self.try_fold((), check(predicate)).break_value()
2368 /// Applies function to the elements of iterator and returns
2369 /// the first non-none result.
2371 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2376 /// let a = ["lol", "NaN", "2", "5"];
2378 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2380 /// assert_eq!(first_number, Some(2));
2383 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2384 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2387 F: FnMut(Self::Item) -> Option<B>,
2390 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2391 move |(), x| match f(x) {
2392 Some(x) => ControlFlow::Break(x),
2393 None => ControlFlow::CONTINUE,
2397 self.try_fold((), check(f)).break_value()
2400 /// Applies function to the elements of iterator and returns
2401 /// the first true result or the first error.
2406 /// #![feature(try_find)]
2408 /// let a = ["1", "2", "lol", "NaN", "5"];
2410 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2411 /// Ok(s.parse::<i32>()? == search)
2414 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2415 /// assert_eq!(result, Ok(Some(&"2")));
2417 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2418 /// assert!(result.is_err());
2421 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2422 #[cfg(not(bootstrap))]
2423 fn try_find<F, R, E>(&mut self, f: F) -> Result<Option<Self::Item>, E>
2426 F: FnMut(&Self::Item) -> R,
2427 R: Try<Output = bool>,
2428 // FIXME: This bound is rather strange, but means minimal breakage on nightly.
2429 // See #85115 for the issue tracking a holistic solution for this and try_map.
2430 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2433 fn check<F, T, R, E>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, E>>
2436 R: Try<Output = bool>,
2437 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2439 move |(), x| match f(&x).branch() {
2440 ControlFlow::Continue(false) => ControlFlow::CONTINUE,
2441 ControlFlow::Continue(true) => ControlFlow::Break(Ok(x)),
2442 ControlFlow::Break(Err(x)) => ControlFlow::Break(Err(x)),
2446 self.try_fold((), check(f)).break_value().transpose()
2449 /// We're bootstrapping.
2451 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2453 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2456 F: FnMut(&Self::Item) -> R,
2457 R: Try<Output = bool>,
2460 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, R::Error>>
2463 R: Try<Output = bool>,
2465 move |(), x| match f(&x).into_result() {
2466 Ok(false) => ControlFlow::CONTINUE,
2467 Ok(true) => ControlFlow::Break(Ok(x)),
2468 Err(x) => ControlFlow::Break(Err(x)),
2472 self.try_fold((), check(f)).break_value().transpose()
2475 /// Searches for an element in an iterator, returning its index.
2477 /// `position()` takes a closure that returns `true` or `false`. It applies
2478 /// this closure to each element of the iterator, and if one of them
2479 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2480 /// them return `false`, it returns [`None`].
2482 /// `position()` is short-circuiting; in other words, it will stop
2483 /// processing as soon as it finds a `true`.
2485 /// # Overflow Behavior
2487 /// The method does no guarding against overflows, so if there are more
2488 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2489 /// result or panics. If debug assertions are enabled, a panic is
2494 /// This function might panic if the iterator has more than `usize::MAX`
2495 /// non-matching elements.
2497 /// [`Some(index)`]: Some
2504 /// let a = [1, 2, 3];
2506 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2508 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2511 /// Stopping at the first `true`:
2514 /// let a = [1, 2, 3, 4];
2516 /// let mut iter = a.iter();
2518 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2520 /// // we can still use `iter`, as there are more elements.
2521 /// assert_eq!(iter.next(), Some(&3));
2523 /// // The returned index depends on iterator state
2524 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 fn position<P>(&mut self, predicate: P) -> Option<usize>
2532 P: FnMut(Self::Item) -> bool,
2536 mut predicate: impl FnMut(T) -> bool,
2537 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2538 #[rustc_inherit_overflow_checks]
2540 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2544 self.try_fold(0, check(predicate)).break_value()
2547 /// Searches for an element in an iterator from the right, returning its
2550 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2551 /// this closure to each element of the iterator, starting from the end,
2552 /// and if one of them returns `true`, then `rposition()` returns
2553 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2555 /// `rposition()` is short-circuiting; in other words, it will stop
2556 /// processing as soon as it finds a `true`.
2558 /// [`Some(index)`]: Some
2565 /// let a = [1, 2, 3];
2567 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2569 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2572 /// Stopping at the first `true`:
2575 /// let a = [1, 2, 3];
2577 /// let mut iter = a.iter();
2579 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2581 /// // we can still use `iter`, as there are more elements.
2582 /// assert_eq!(iter.next(), Some(&1));
2585 #[stable(feature = "rust1", since = "1.0.0")]
2586 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2588 P: FnMut(Self::Item) -> bool,
2589 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2591 // No need for an overflow check here, because `ExactSizeIterator`
2592 // implies that the number of elements fits into a `usize`.
2595 mut predicate: impl FnMut(T) -> bool,
2596 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2599 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2604 self.try_rfold(n, check(predicate)).break_value()
2607 /// Returns the maximum element of an iterator.
2609 /// If several elements are equally maximum, the last element is
2610 /// returned. If the iterator is empty, [`None`] is returned.
2612 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2613 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2616 /// vec![2.4, f32::NAN, 1.3]
2618 /// .reduce(f32::max)
2629 /// let a = [1, 2, 3];
2630 /// let b: Vec<u32> = Vec::new();
2632 /// assert_eq!(a.iter().max(), Some(&3));
2633 /// assert_eq!(b.iter().max(), None);
2636 #[stable(feature = "rust1", since = "1.0.0")]
2637 fn max(self) -> Option<Self::Item>
2642 self.max_by(Ord::cmp)
2645 /// Returns the minimum element of an iterator.
2647 /// If several elements are equally minimum, the first element is returned.
2648 /// If the iterator is empty, [`None`] is returned.
2650 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2651 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2654 /// vec![2.4, f32::NAN, 1.3]
2656 /// .reduce(f32::min)
2667 /// let a = [1, 2, 3];
2668 /// let b: Vec<u32> = Vec::new();
2670 /// assert_eq!(a.iter().min(), Some(&1));
2671 /// assert_eq!(b.iter().min(), None);
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 fn min(self) -> Option<Self::Item>
2680 self.min_by(Ord::cmp)
2683 /// Returns the element that gives the maximum value from the
2684 /// specified function.
2686 /// If several elements are equally maximum, the last element is
2687 /// returned. If the iterator is empty, [`None`] is returned.
2692 /// let a = [-3_i32, 0, 1, 5, -10];
2693 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2696 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2697 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2700 F: FnMut(&Self::Item) -> B,
2703 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2708 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2712 let (_, x) = self.map(key(f)).max_by(compare)?;
2716 /// Returns the element that gives the maximum value with respect to the
2717 /// specified comparison function.
2719 /// If several elements are equally maximum, the last element is
2720 /// returned. If the iterator is empty, [`None`] is returned.
2725 /// let a = [-3_i32, 0, 1, 5, -10];
2726 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2729 #[stable(feature = "iter_max_by", since = "1.15.0")]
2730 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2733 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2736 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2737 move |x, y| cmp::max_by(x, y, &mut compare)
2740 self.reduce(fold(compare))
2743 /// Returns the element that gives the minimum value from the
2744 /// specified function.
2746 /// If several elements are equally minimum, the first element is
2747 /// returned. If the iterator is empty, [`None`] is returned.
2752 /// let a = [-3_i32, 0, 1, 5, -10];
2753 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2756 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2757 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2760 F: FnMut(&Self::Item) -> B,
2763 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2768 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2772 let (_, x) = self.map(key(f)).min_by(compare)?;
2776 /// Returns the element that gives the minimum value with respect to the
2777 /// specified comparison function.
2779 /// If several elements are equally minimum, the first element is
2780 /// returned. If the iterator is empty, [`None`] is returned.
2785 /// let a = [-3_i32, 0, 1, 5, -10];
2786 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2789 #[stable(feature = "iter_min_by", since = "1.15.0")]
2790 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2793 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2796 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2797 move |x, y| cmp::min_by(x, y, &mut compare)
2800 self.reduce(fold(compare))
2803 /// Reverses an iterator's direction.
2805 /// Usually, iterators iterate from left to right. After using `rev()`,
2806 /// an iterator will instead iterate from right to left.
2808 /// This is only possible if the iterator has an end, so `rev()` only
2809 /// works on [`DoubleEndedIterator`]s.
2814 /// let a = [1, 2, 3];
2816 /// let mut iter = a.iter().rev();
2818 /// assert_eq!(iter.next(), Some(&3));
2819 /// assert_eq!(iter.next(), Some(&2));
2820 /// assert_eq!(iter.next(), Some(&1));
2822 /// assert_eq!(iter.next(), None);
2825 #[doc(alias = "reverse")]
2826 #[stable(feature = "rust1", since = "1.0.0")]
2827 fn rev(self) -> Rev<Self>
2829 Self: Sized + DoubleEndedIterator,
2834 /// Converts an iterator of pairs into a pair of containers.
2836 /// `unzip()` consumes an entire iterator of pairs, producing two
2837 /// collections: one from the left elements of the pairs, and one
2838 /// from the right elements.
2840 /// This function is, in some sense, the opposite of [`zip`].
2842 /// [`zip`]: Iterator::zip
2849 /// let a = [(1, 2), (3, 4)];
2851 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2853 /// assert_eq!(left, [1, 3]);
2854 /// assert_eq!(right, [2, 4]);
2856 #[stable(feature = "rust1", since = "1.0.0")]
2857 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2859 FromA: Default + Extend<A>,
2860 FromB: Default + Extend<B>,
2861 Self: Sized + Iterator<Item = (A, B)>,
2863 fn extend<'a, A, B>(
2864 ts: &'a mut impl Extend<A>,
2865 us: &'a mut impl Extend<B>,
2866 ) -> impl FnMut((), (A, B)) + 'a {
2873 let mut ts: FromA = Default::default();
2874 let mut us: FromB = Default::default();
2876 let (lower_bound, _) = self.size_hint();
2877 if lower_bound > 0 {
2878 ts.extend_reserve(lower_bound);
2879 us.extend_reserve(lower_bound);
2882 self.fold((), extend(&mut ts, &mut us));
2887 /// Creates an iterator which copies all of its elements.
2889 /// This is useful when you have an iterator over `&T`, but you need an
2890 /// iterator over `T`.
2897 /// let a = [1, 2, 3];
2899 /// let v_copied: Vec<_> = a.iter().copied().collect();
2901 /// // copied is the same as .map(|&x| x)
2902 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2904 /// assert_eq!(v_copied, vec![1, 2, 3]);
2905 /// assert_eq!(v_map, vec![1, 2, 3]);
2907 #[stable(feature = "iter_copied", since = "1.36.0")]
2908 fn copied<'a, T: 'a>(self) -> Copied<Self>
2910 Self: Sized + Iterator<Item = &'a T>,
2916 /// Creates an iterator which [`clone`]s all of its elements.
2918 /// This is useful when you have an iterator over `&T`, but you need an
2919 /// iterator over `T`.
2921 /// [`clone`]: Clone::clone
2928 /// let a = [1, 2, 3];
2930 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2932 /// // cloned is the same as .map(|&x| x), for integers
2933 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2935 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2936 /// assert_eq!(v_map, vec![1, 2, 3]);
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2941 Self: Sized + Iterator<Item = &'a T>,
2947 /// Repeats an iterator endlessly.
2949 /// Instead of stopping at [`None`], the iterator will instead start again,
2950 /// from the beginning. After iterating again, it will start at the
2951 /// beginning again. And again. And again. Forever.
2958 /// let a = [1, 2, 3];
2960 /// let mut it = a.iter().cycle();
2962 /// assert_eq!(it.next(), Some(&1));
2963 /// assert_eq!(it.next(), Some(&2));
2964 /// assert_eq!(it.next(), Some(&3));
2965 /// assert_eq!(it.next(), Some(&1));
2966 /// assert_eq!(it.next(), Some(&2));
2967 /// assert_eq!(it.next(), Some(&3));
2968 /// assert_eq!(it.next(), Some(&1));
2970 #[stable(feature = "rust1", since = "1.0.0")]
2972 fn cycle(self) -> Cycle<Self>
2974 Self: Sized + Clone,
2979 /// Sums the elements of an iterator.
2981 /// Takes each element, adds them together, and returns the result.
2983 /// An empty iterator returns the zero value of the type.
2987 /// When calling `sum()` and a primitive integer type is being returned, this
2988 /// method will panic if the computation overflows and debug assertions are
2996 /// let a = [1, 2, 3];
2997 /// let sum: i32 = a.iter().sum();
2999 /// assert_eq!(sum, 6);
3001 #[stable(feature = "iter_arith", since = "1.11.0")]
3002 fn sum<S>(self) -> S
3010 /// Iterates over the entire iterator, multiplying all the elements
3012 /// An empty iterator returns the one value of the type.
3016 /// When calling `product()` and a primitive integer type is being returned,
3017 /// method will panic if the computation overflows and debug assertions are
3023 /// fn factorial(n: u32) -> u32 {
3024 /// (1..=n).product()
3026 /// assert_eq!(factorial(0), 1);
3027 /// assert_eq!(factorial(1), 1);
3028 /// assert_eq!(factorial(5), 120);
3030 #[stable(feature = "iter_arith", since = "1.11.0")]
3031 fn product<P>(self) -> P
3034 P: Product<Self::Item>,
3036 Product::product(self)
3039 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3045 /// use std::cmp::Ordering;
3047 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3048 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3049 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3051 #[stable(feature = "iter_order", since = "1.5.0")]
3052 fn cmp<I>(self, other: I) -> Ordering
3054 I: IntoIterator<Item = Self::Item>,
3058 self.cmp_by(other, |x, y| x.cmp(&y))
3061 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3062 /// of another with respect to the specified comparison function.
3069 /// #![feature(iter_order_by)]
3071 /// use std::cmp::Ordering;
3073 /// let xs = [1, 2, 3, 4];
3074 /// let ys = [1, 4, 9, 16];
3076 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3077 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3078 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3080 #[unstable(feature = "iter_order_by", issue = "64295")]
3081 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
3085 F: FnMut(Self::Item, I::Item) -> Ordering,
3087 let mut other = other.into_iter();
3090 let x = match self.next() {
3092 if other.next().is_none() {
3093 return Ordering::Equal;
3095 return Ordering::Less;
3101 let y = match other.next() {
3102 None => return Ordering::Greater,
3107 Ordering::Equal => (),
3108 non_eq => return non_eq,
3113 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3119 /// use std::cmp::Ordering;
3121 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3122 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3123 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3125 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3127 #[stable(feature = "iter_order", since = "1.5.0")]
3128 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3131 Self::Item: PartialOrd<I::Item>,
3134 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3137 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3138 /// of another with respect to the specified comparison function.
3145 /// #![feature(iter_order_by)]
3147 /// use std::cmp::Ordering;
3149 /// let xs = [1.0, 2.0, 3.0, 4.0];
3150 /// let ys = [1.0, 4.0, 9.0, 16.0];
3153 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3154 /// Some(Ordering::Less)
3157 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3158 /// Some(Ordering::Equal)
3161 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3162 /// Some(Ordering::Greater)
3165 #[unstable(feature = "iter_order_by", issue = "64295")]
3166 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3170 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3172 let mut other = other.into_iter();
3175 let x = match self.next() {
3177 if other.next().is_none() {
3178 return Some(Ordering::Equal);
3180 return Some(Ordering::Less);
3186 let y = match other.next() {
3187 None => return Some(Ordering::Greater),
3191 match partial_cmp(x, y) {
3192 Some(Ordering::Equal) => (),
3193 non_eq => return non_eq,
3198 /// Determines if the elements of this [`Iterator`] are equal to those of
3204 /// assert_eq!([1].iter().eq([1].iter()), true);
3205 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3207 #[stable(feature = "iter_order", since = "1.5.0")]
3208 fn eq<I>(self, other: I) -> bool
3211 Self::Item: PartialEq<I::Item>,
3214 self.eq_by(other, |x, y| x == y)
3217 /// Determines if the elements of this [`Iterator`] are equal to those of
3218 /// another with respect to the specified equality function.
3225 /// #![feature(iter_order_by)]
3227 /// let xs = [1, 2, 3, 4];
3228 /// let ys = [1, 4, 9, 16];
3230 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3232 #[unstable(feature = "iter_order_by", issue = "64295")]
3233 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3237 F: FnMut(Self::Item, I::Item) -> bool,
3239 let mut other = other.into_iter();
3242 let x = match self.next() {
3243 None => return other.next().is_none(),
3247 let y = match other.next() {
3248 None => return false,
3258 /// Determines if the elements of this [`Iterator`] are unequal to those of
3264 /// assert_eq!([1].iter().ne([1].iter()), false);
3265 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3267 #[stable(feature = "iter_order", since = "1.5.0")]
3268 fn ne<I>(self, other: I) -> bool
3271 Self::Item: PartialEq<I::Item>,
3277 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3278 /// less than those of another.
3283 /// assert_eq!([1].iter().lt([1].iter()), false);
3284 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3285 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3286 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3288 #[stable(feature = "iter_order", since = "1.5.0")]
3289 fn lt<I>(self, other: I) -> bool
3292 Self::Item: PartialOrd<I::Item>,
3295 self.partial_cmp(other) == Some(Ordering::Less)
3298 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3299 /// less or equal to those of another.
3304 /// assert_eq!([1].iter().le([1].iter()), true);
3305 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3306 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3307 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3309 #[stable(feature = "iter_order", since = "1.5.0")]
3310 fn le<I>(self, other: I) -> bool
3313 Self::Item: PartialOrd<I::Item>,
3316 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3319 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3320 /// greater than those of another.
3325 /// assert_eq!([1].iter().gt([1].iter()), false);
3326 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3327 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3328 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3330 #[stable(feature = "iter_order", since = "1.5.0")]
3331 fn gt<I>(self, other: I) -> bool
3334 Self::Item: PartialOrd<I::Item>,
3337 self.partial_cmp(other) == Some(Ordering::Greater)
3340 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3341 /// greater than or equal to those of another.
3346 /// assert_eq!([1].iter().ge([1].iter()), true);
3347 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3348 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3349 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3351 #[stable(feature = "iter_order", since = "1.5.0")]
3352 fn ge<I>(self, other: I) -> bool
3355 Self::Item: PartialOrd<I::Item>,
3358 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3361 /// Checks if the elements of this iterator are sorted.
3363 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3364 /// iterator yields exactly zero or one element, `true` is returned.
3366 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3367 /// implies that this function returns `false` if any two consecutive items are not
3373 /// #![feature(is_sorted)]
3375 /// assert!([1, 2, 2, 9].iter().is_sorted());
3376 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3377 /// assert!([0].iter().is_sorted());
3378 /// assert!(std::iter::empty::<i32>().is_sorted());
3379 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3382 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3383 fn is_sorted(self) -> bool
3386 Self::Item: PartialOrd,
3388 self.is_sorted_by(PartialOrd::partial_cmp)
3391 /// Checks if the elements of this iterator are sorted using the given comparator function.
3393 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3394 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3395 /// [`is_sorted`]; see its documentation for more information.
3400 /// #![feature(is_sorted)]
3402 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3403 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3404 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3405 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3406 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3409 /// [`is_sorted`]: Iterator::is_sorted
3410 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3411 fn is_sorted_by<F>(mut self, compare: F) -> bool
3414 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3419 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3420 ) -> impl FnMut(T) -> bool + 'a {
3422 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3430 let mut last = match self.next() {
3432 None => return true,
3435 self.all(check(&mut last, compare))
3438 /// Checks if the elements of this iterator are sorted using the given key extraction
3441 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3442 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3443 /// its documentation for more information.
3445 /// [`is_sorted`]: Iterator::is_sorted
3450 /// #![feature(is_sorted)]
3452 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3453 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3456 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3457 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3460 F: FnMut(Self::Item) -> K,
3463 self.map(f).is_sorted()
3466 /// See [TrustedRandomAccess]
3467 // The unusual name is to avoid name collisions in method resolution
3471 #[unstable(feature = "trusted_random_access", issue = "none")]
3472 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3474 Self: TrustedRandomAccess,
3476 unreachable!("Always specialized");
3480 #[stable(feature = "rust1", since = "1.0.0")]
3481 impl<I: Iterator + ?Sized> Iterator for &mut I {
3482 type Item = I::Item;
3483 fn next(&mut self) -> Option<I::Item> {
3486 fn size_hint(&self) -> (usize, Option<usize>) {
3487 (**self).size_hint()
3489 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3490 (**self).advance_by(n)
3492 fn nth(&mut self, n: usize) -> Option<Self::Item> {