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::TrustedRandomAccessNoCoerce;
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 `self.next()`, `self.nth(step-1)`,
337 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
338 /// `advance_n_and_return_first(&mut self, step)`,
339 /// `advance_n_and_return_first(&mut self, step)`, …
340 /// Which way is used may change for some iterators for performance reasons.
341 /// The second way will advance the iterator earlier and may consume more items.
343 /// `advance_n_and_return_first` is the equivalent of:
345 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
349 /// let next = iter.next();
359 /// The method will panic if the given step is `0`.
366 /// let a = [0, 1, 2, 3, 4, 5];
367 /// let mut iter = a.iter().step_by(2);
369 /// assert_eq!(iter.next(), Some(&0));
370 /// assert_eq!(iter.next(), Some(&2));
371 /// assert_eq!(iter.next(), Some(&4));
372 /// assert_eq!(iter.next(), None);
375 #[stable(feature = "iterator_step_by", since = "1.28.0")]
376 fn step_by(self, step: usize) -> StepBy<Self>
380 StepBy::new(self, step)
383 /// Takes two iterators and creates a new iterator over both in sequence.
385 /// `chain()` will return a new iterator which will first iterate over
386 /// values from the first iterator and then over values from the second
389 /// In other words, it links two iterators together, in a chain. 🔗
391 /// [`once`] is commonly used to adapt a single value into a chain of
392 /// other kinds of iteration.
399 /// let a1 = [1, 2, 3];
400 /// let a2 = [4, 5, 6];
402 /// let mut iter = a1.iter().chain(a2.iter());
404 /// assert_eq!(iter.next(), Some(&1));
405 /// assert_eq!(iter.next(), Some(&2));
406 /// assert_eq!(iter.next(), Some(&3));
407 /// assert_eq!(iter.next(), Some(&4));
408 /// assert_eq!(iter.next(), Some(&5));
409 /// assert_eq!(iter.next(), Some(&6));
410 /// assert_eq!(iter.next(), None);
413 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
414 /// anything that can be converted into an [`Iterator`], not just an
415 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
416 /// [`IntoIterator`], and so can be passed to `chain()` directly:
419 /// let s1 = &[1, 2, 3];
420 /// let s2 = &[4, 5, 6];
422 /// let mut iter = s1.iter().chain(s2);
424 /// assert_eq!(iter.next(), Some(&1));
425 /// assert_eq!(iter.next(), Some(&2));
426 /// assert_eq!(iter.next(), Some(&3));
427 /// assert_eq!(iter.next(), Some(&4));
428 /// assert_eq!(iter.next(), Some(&5));
429 /// assert_eq!(iter.next(), Some(&6));
430 /// assert_eq!(iter.next(), None);
433 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
437 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
438 /// use std::os::windows::ffi::OsStrExt;
439 /// s.encode_wide().chain(std::iter::once(0)).collect()
443 /// [`once`]: crate::iter::once
444 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
446 #[stable(feature = "rust1", since = "1.0.0")]
447 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
450 U: IntoIterator<Item = Self::Item>,
452 Chain::new(self, other.into_iter())
455 /// 'Zips up' two iterators into a single iterator of pairs.
457 /// `zip()` returns a new iterator that will iterate over two other
458 /// iterators, returning a tuple where the first element comes from the
459 /// first iterator, and the second element comes from the second iterator.
461 /// In other words, it zips two iterators together, into a single one.
463 /// If either iterator returns [`None`], [`next`] from the zipped iterator
464 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
465 /// short-circuit and `next` will not be called on the second iterator.
472 /// let a1 = [1, 2, 3];
473 /// let a2 = [4, 5, 6];
475 /// let mut iter = a1.iter().zip(a2.iter());
477 /// assert_eq!(iter.next(), Some((&1, &4)));
478 /// assert_eq!(iter.next(), Some((&2, &5)));
479 /// assert_eq!(iter.next(), Some((&3, &6)));
480 /// assert_eq!(iter.next(), None);
483 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
484 /// anything that can be converted into an [`Iterator`], not just an
485 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
486 /// [`IntoIterator`], and so can be passed to `zip()` directly:
489 /// let s1 = &[1, 2, 3];
490 /// let s2 = &[4, 5, 6];
492 /// let mut iter = s1.iter().zip(s2);
494 /// assert_eq!(iter.next(), Some((&1, &4)));
495 /// assert_eq!(iter.next(), Some((&2, &5)));
496 /// assert_eq!(iter.next(), Some((&3, &6)));
497 /// assert_eq!(iter.next(), None);
500 /// `zip()` is often used to zip an infinite iterator to a finite one.
501 /// This works because the finite iterator will eventually return [`None`],
502 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
505 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
507 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
509 /// assert_eq!((0, 'f'), enumerate[0]);
510 /// assert_eq!((0, 'f'), zipper[0]);
512 /// assert_eq!((1, 'o'), enumerate[1]);
513 /// assert_eq!((1, 'o'), zipper[1]);
515 /// assert_eq!((2, 'o'), enumerate[2]);
516 /// assert_eq!((2, 'o'), zipper[2]);
519 /// [`enumerate`]: Iterator::enumerate
520 /// [`next`]: Iterator::next
522 #[stable(feature = "rust1", since = "1.0.0")]
523 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
528 Zip::new(self, other.into_iter())
531 /// Creates a new iterator which places a copy of `separator` between adjacent
532 /// items of the original iterator.
534 /// In case `separator` does not implement [`Clone`] or needs to be
535 /// computed every time, use [`intersperse_with`].
542 /// #![feature(iter_intersperse)]
544 /// let mut a = [0, 1, 2].iter().intersperse(&100);
545 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
546 /// assert_eq!(a.next(), Some(&100)); // The separator.
547 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
548 /// assert_eq!(a.next(), Some(&100)); // The separator.
549 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
550 /// assert_eq!(a.next(), None); // The iterator is finished.
553 /// `intersperse` can be very useful to join an iterator's items using a common element:
555 /// #![feature(iter_intersperse)]
557 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
558 /// assert_eq!(hello, "Hello World !");
561 /// [`Clone`]: crate::clone::Clone
562 /// [`intersperse_with`]: Iterator::intersperse_with
564 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
565 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
570 Intersperse::new(self, separator)
573 /// Creates a new iterator which places an item generated by `separator`
574 /// between adjacent items of the original iterator.
576 /// The closure will be called exactly once each time an item is placed
577 /// between two adjacent items from the underlying iterator; specifically,
578 /// the closure is not called if the underlying iterator yields less than
579 /// two items and after the last item is yielded.
581 /// If the iterator's item implements [`Clone`], it may be easier to use
589 /// #![feature(iter_intersperse)]
591 /// #[derive(PartialEq, Debug)]
592 /// struct NotClone(usize);
594 /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
595 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
597 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
598 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
599 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
600 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
601 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
602 /// assert_eq!(it.next(), None); // The iterator is finished.
605 /// `intersperse_with` can be used in situations where the separator needs
608 /// #![feature(iter_intersperse)]
610 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
612 /// // The closure mutably borrows its context to generate an item.
613 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
614 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
616 /// let result = src.intersperse_with(separator).collect::<String>();
617 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
619 /// [`Clone`]: crate::clone::Clone
620 /// [`intersperse`]: Iterator::intersperse
622 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
623 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
626 G: FnMut() -> Self::Item,
628 IntersperseWith::new(self, separator)
631 /// Takes a closure and creates an iterator which calls that closure on each
634 /// `map()` transforms one iterator into another, by means of its argument:
635 /// something that implements [`FnMut`]. It produces a new iterator which
636 /// calls this closure on each element of the original iterator.
638 /// If you are good at thinking in types, you can think of `map()` like this:
639 /// If you have an iterator that gives you elements of some type `A`, and
640 /// you want an iterator of some other type `B`, you can use `map()`,
641 /// passing a closure that takes an `A` and returns a `B`.
643 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
644 /// lazy, it is best used when you're already working with other iterators.
645 /// If you're doing some sort of looping for a side effect, it's considered
646 /// more idiomatic to use [`for`] than `map()`.
648 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
649 /// [`FnMut`]: crate::ops::FnMut
656 /// let a = [1, 2, 3];
658 /// let mut iter = a.iter().map(|x| 2 * x);
660 /// assert_eq!(iter.next(), Some(2));
661 /// assert_eq!(iter.next(), Some(4));
662 /// assert_eq!(iter.next(), Some(6));
663 /// assert_eq!(iter.next(), None);
666 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
669 /// # #![allow(unused_must_use)]
670 /// // don't do this:
671 /// (0..5).map(|x| println!("{}", x));
673 /// // it won't even execute, as it is lazy. Rust will warn you about this.
675 /// // Instead, use for:
677 /// println!("{}", x);
681 #[stable(feature = "rust1", since = "1.0.0")]
682 fn map<B, F>(self, f: F) -> Map<Self, F>
685 F: FnMut(Self::Item) -> B,
690 /// Calls a closure on each element of an iterator.
692 /// This is equivalent to using a [`for`] loop on the iterator, although
693 /// `break` and `continue` are not possible from a closure. It's generally
694 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
695 /// when processing items at the end of longer iterator chains. In some
696 /// cases `for_each` may also be faster than a loop, because it will use
697 /// internal iteration on adapters like `Chain`.
699 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
706 /// use std::sync::mpsc::channel;
708 /// let (tx, rx) = channel();
709 /// (0..5).map(|x| x * 2 + 1)
710 /// .for_each(move |x| tx.send(x).unwrap());
712 /// let v: Vec<_> = rx.iter().collect();
713 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
716 /// For such a small example, a `for` loop may be cleaner, but `for_each`
717 /// might be preferable to keep a functional style with longer iterators:
720 /// (0..5).flat_map(|x| x * 100 .. x * 110)
722 /// .filter(|&(i, x)| (i + x) % 3 == 0)
723 /// .for_each(|(i, x)| println!("{}:{}", i, x));
726 #[stable(feature = "iterator_for_each", since = "1.21.0")]
727 fn for_each<F>(self, f: F)
730 F: FnMut(Self::Item),
733 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
734 move |(), item| f(item)
737 self.fold((), call(f));
740 /// Creates an iterator which uses a closure to determine if an element
741 /// should be yielded.
743 /// Given an element the closure must return `true` or `false`. The returned
744 /// iterator will yield only the elements for which the closure returns
752 /// let a = [0i32, 1, 2];
754 /// let mut iter = a.iter().filter(|x| x.is_positive());
756 /// assert_eq!(iter.next(), Some(&1));
757 /// assert_eq!(iter.next(), Some(&2));
758 /// assert_eq!(iter.next(), None);
761 /// Because the closure passed to `filter()` takes a reference, and many
762 /// iterators iterate over references, this leads to a possibly confusing
763 /// situation, where the type of the closure is a double reference:
766 /// let a = [0, 1, 2];
768 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
770 /// assert_eq!(iter.next(), Some(&2));
771 /// assert_eq!(iter.next(), None);
774 /// It's common to instead use destructuring on the argument to strip away
778 /// let a = [0, 1, 2];
780 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
782 /// assert_eq!(iter.next(), Some(&2));
783 /// assert_eq!(iter.next(), None);
789 /// let a = [0, 1, 2];
791 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
793 /// assert_eq!(iter.next(), Some(&2));
794 /// assert_eq!(iter.next(), None);
799 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
801 #[stable(feature = "rust1", since = "1.0.0")]
802 fn filter<P>(self, predicate: P) -> Filter<Self, P>
805 P: FnMut(&Self::Item) -> bool,
807 Filter::new(self, predicate)
810 /// Creates an iterator that both filters and maps.
812 /// The returned iterator yields only the `value`s for which the supplied
813 /// closure returns `Some(value)`.
815 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
816 /// concise. The example below shows how a `map().filter().map()` can be
817 /// shortened to a single call to `filter_map`.
819 /// [`filter`]: Iterator::filter
820 /// [`map`]: Iterator::map
827 /// let a = ["1", "two", "NaN", "four", "5"];
829 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
831 /// assert_eq!(iter.next(), Some(1));
832 /// assert_eq!(iter.next(), Some(5));
833 /// assert_eq!(iter.next(), None);
836 /// Here's the same example, but with [`filter`] and [`map`]:
839 /// let a = ["1", "two", "NaN", "four", "5"];
840 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
841 /// assert_eq!(iter.next(), Some(1));
842 /// assert_eq!(iter.next(), Some(5));
843 /// assert_eq!(iter.next(), None);
846 #[stable(feature = "rust1", since = "1.0.0")]
847 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
850 F: FnMut(Self::Item) -> Option<B>,
852 FilterMap::new(self, f)
855 /// Creates an iterator which gives the current iteration count as well as
858 /// The iterator returned yields pairs `(i, val)`, where `i` is the
859 /// current index of iteration and `val` is the value returned by the
862 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
863 /// different sized integer, the [`zip`] function provides similar
866 /// # Overflow Behavior
868 /// The method does no guarding against overflows, so enumerating more than
869 /// [`usize::MAX`] elements either produces the wrong result or panics. If
870 /// debug assertions are enabled, a panic is guaranteed.
874 /// The returned iterator might panic if the to-be-returned index would
875 /// overflow a [`usize`].
877 /// [`usize`]: type@usize
878 /// [`zip`]: Iterator::zip
883 /// let a = ['a', 'b', 'c'];
885 /// let mut iter = a.iter().enumerate();
887 /// assert_eq!(iter.next(), Some((0, &'a')));
888 /// assert_eq!(iter.next(), Some((1, &'b')));
889 /// assert_eq!(iter.next(), Some((2, &'c')));
890 /// assert_eq!(iter.next(), None);
893 #[stable(feature = "rust1", since = "1.0.0")]
894 fn enumerate(self) -> Enumerate<Self>
901 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
902 /// to look at the next element of the iterator without consuming it. See
903 /// their documentation for more information.
905 /// Note that the underlying iterator is still advanced when [`peek`] or
906 /// [`peek_mut`] are called for the first time: In order to retrieve the
907 /// next element, [`next`] is called on the underlying iterator, hence any
908 /// side effects (i.e. anything other than fetching the next value) of
909 /// the [`next`] method will occur.
917 /// let xs = [1, 2, 3];
919 /// let mut iter = xs.iter().peekable();
921 /// // peek() lets us see into the future
922 /// assert_eq!(iter.peek(), Some(&&1));
923 /// assert_eq!(iter.next(), Some(&1));
925 /// assert_eq!(iter.next(), Some(&2));
927 /// // we can peek() multiple times, the iterator won't advance
928 /// assert_eq!(iter.peek(), Some(&&3));
929 /// assert_eq!(iter.peek(), Some(&&3));
931 /// assert_eq!(iter.next(), Some(&3));
933 /// // after the iterator is finished, so is peek()
934 /// assert_eq!(iter.peek(), None);
935 /// assert_eq!(iter.next(), None);
938 /// Using [`peek_mut`] to mutate the next item without advancing the
942 /// let xs = [1, 2, 3];
944 /// let mut iter = xs.iter().peekable();
946 /// // `peek_mut()` lets us see into the future
947 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
948 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
949 /// assert_eq!(iter.next(), Some(&1));
951 /// if let Some(mut p) = iter.peek_mut() {
952 /// assert_eq!(*p, &2);
953 /// // put a value into the iterator
957 /// // The value reappears as the iterator continues
958 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
960 /// [`peek`]: Peekable::peek
961 /// [`peek_mut`]: Peekable::peek_mut
962 /// [`next`]: Iterator::next
964 #[stable(feature = "rust1", since = "1.0.0")]
965 fn peekable(self) -> Peekable<Self>
972 /// Creates an iterator that [`skip`]s elements based on a predicate.
974 /// [`skip`]: Iterator::skip
976 /// `skip_while()` takes a closure as an argument. It will call this
977 /// closure on each element of the iterator, and ignore elements
978 /// until it returns `false`.
980 /// After `false` is returned, `skip_while()`'s job is over, and the
981 /// rest of the elements are yielded.
988 /// let a = [-1i32, 0, 1];
990 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
992 /// assert_eq!(iter.next(), Some(&0));
993 /// assert_eq!(iter.next(), Some(&1));
994 /// assert_eq!(iter.next(), None);
997 /// Because the closure passed to `skip_while()` takes a reference, and many
998 /// iterators iterate over references, this leads to a possibly confusing
999 /// situation, where the type of the closure argument is a double reference:
1002 /// let a = [-1, 0, 1];
1004 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1006 /// assert_eq!(iter.next(), Some(&0));
1007 /// assert_eq!(iter.next(), Some(&1));
1008 /// assert_eq!(iter.next(), None);
1011 /// Stopping after an initial `false`:
1014 /// let a = [-1, 0, 1, -2];
1016 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1018 /// assert_eq!(iter.next(), Some(&0));
1019 /// assert_eq!(iter.next(), Some(&1));
1021 /// // while this would have been false, since we already got a false,
1022 /// // skip_while() isn't used any more
1023 /// assert_eq!(iter.next(), Some(&-2));
1025 /// assert_eq!(iter.next(), None);
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1032 P: FnMut(&Self::Item) -> bool,
1034 SkipWhile::new(self, predicate)
1037 /// Creates an iterator that yields elements based on a predicate.
1039 /// `take_while()` takes a closure as an argument. It will call this
1040 /// closure on each element of the iterator, and yield elements
1041 /// while it returns `true`.
1043 /// After `false` is returned, `take_while()`'s job is over, and the
1044 /// rest of the elements are ignored.
1051 /// let a = [-1i32, 0, 1];
1053 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1055 /// assert_eq!(iter.next(), Some(&-1));
1056 /// assert_eq!(iter.next(), None);
1059 /// Because the closure passed to `take_while()` takes a reference, and many
1060 /// iterators iterate over references, this leads to a possibly confusing
1061 /// situation, where the type of the closure is a double reference:
1064 /// let a = [-1, 0, 1];
1066 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1068 /// assert_eq!(iter.next(), Some(&-1));
1069 /// assert_eq!(iter.next(), None);
1072 /// Stopping after an initial `false`:
1075 /// let a = [-1, 0, 1, -2];
1077 /// let mut iter = a.iter().take_while(|x| **x < 0);
1079 /// assert_eq!(iter.next(), Some(&-1));
1081 /// // We have more elements that are less than zero, but since we already
1082 /// // got a false, take_while() isn't used any more
1083 /// assert_eq!(iter.next(), None);
1086 /// Because `take_while()` needs to look at the value in order to see if it
1087 /// should be included or not, consuming iterators will see that it is
1091 /// let a = [1, 2, 3, 4];
1092 /// let mut iter = a.iter();
1094 /// let result: Vec<i32> = iter.by_ref()
1095 /// .take_while(|n| **n != 3)
1099 /// assert_eq!(result, &[1, 2]);
1101 /// let result: Vec<i32> = iter.cloned().collect();
1103 /// assert_eq!(result, &[4]);
1106 /// The `3` is no longer there, because it was consumed in order to see if
1107 /// the iteration should stop, but wasn't placed back into the iterator.
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1113 P: FnMut(&Self::Item) -> bool,
1115 TakeWhile::new(self, predicate)
1118 /// Creates an iterator that both yields elements based on a predicate and maps.
1120 /// `map_while()` takes a closure as an argument. It will call this
1121 /// closure on each element of the iterator, and yield elements
1122 /// while it returns [`Some(_)`][`Some`].
1129 /// #![feature(iter_map_while)]
1130 /// let a = [-1i32, 4, 0, 1];
1132 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1134 /// assert_eq!(iter.next(), Some(-16));
1135 /// assert_eq!(iter.next(), Some(4));
1136 /// assert_eq!(iter.next(), None);
1139 /// Here's the same example, but with [`take_while`] and [`map`]:
1141 /// [`take_while`]: Iterator::take_while
1142 /// [`map`]: Iterator::map
1145 /// let a = [-1i32, 4, 0, 1];
1147 /// let mut iter = a.iter()
1148 /// .map(|x| 16i32.checked_div(*x))
1149 /// .take_while(|x| x.is_some())
1150 /// .map(|x| x.unwrap());
1152 /// assert_eq!(iter.next(), Some(-16));
1153 /// assert_eq!(iter.next(), Some(4));
1154 /// assert_eq!(iter.next(), None);
1157 /// Stopping after an initial [`None`]:
1160 /// #![feature(iter_map_while)]
1161 /// use std::convert::TryFrom;
1163 /// let a = [0, 1, 2, -3, 4, 5, -6];
1165 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1166 /// let vec = iter.collect::<Vec<_>>();
1168 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1169 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1170 /// assert_eq!(vec, vec![0, 1, 2]);
1173 /// Because `map_while()` needs to look at the value in order to see if it
1174 /// should be included or not, consuming iterators will see that it is
1178 /// #![feature(iter_map_while)]
1179 /// use std::convert::TryFrom;
1181 /// let a = [1, 2, -3, 4];
1182 /// let mut iter = a.iter();
1184 /// let result: Vec<u32> = iter.by_ref()
1185 /// .map_while(|n| u32::try_from(*n).ok())
1188 /// assert_eq!(result, &[1, 2]);
1190 /// let result: Vec<i32> = iter.cloned().collect();
1192 /// assert_eq!(result, &[4]);
1195 /// The `-3` is no longer there, because it was consumed in order to see if
1196 /// the iteration should stop, but wasn't placed back into the iterator.
1198 /// Note that unlike [`take_while`] this iterator is **not** fused.
1199 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1200 /// If you need fused iterator, use [`fuse`].
1202 /// [`fuse`]: Iterator::fuse
1204 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1205 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1208 P: FnMut(Self::Item) -> Option<B>,
1210 MapWhile::new(self, predicate)
1213 /// Creates an iterator that skips the first `n` elements.
1215 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1216 /// iterator is reached (whichever happens first). After that, all the remaining
1217 /// elements are yielded. In particular, if the original iterator is too short,
1218 /// then the returned iterator is empty.
1220 /// Rather than overriding this method directly, instead override the `nth` method.
1227 /// let a = [1, 2, 3];
1229 /// let mut iter = a.iter().skip(2);
1231 /// assert_eq!(iter.next(), Some(&3));
1232 /// assert_eq!(iter.next(), None);
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 fn skip(self, n: usize) -> Skip<Self>
1243 /// Creates an iterator that yields the first `n` elements, or fewer
1244 /// if the underlying iterator ends sooner.
1246 /// `take(n)` yields elements until `n` elements are yielded or the end of
1247 /// the iterator is reached (whichever happens first).
1248 /// The returned iterator is a prefix of length `n` if the original iterator
1249 /// contains at least `n` elements, otherwise it contains all of the
1250 /// (fewer than `n`) elements of the original iterator.
1257 /// let a = [1, 2, 3];
1259 /// let mut iter = a.iter().take(2);
1261 /// assert_eq!(iter.next(), Some(&1));
1262 /// assert_eq!(iter.next(), Some(&2));
1263 /// assert_eq!(iter.next(), None);
1266 /// `take()` is often used with an infinite iterator, to make it finite:
1269 /// let mut iter = (0..).take(3);
1271 /// assert_eq!(iter.next(), Some(0));
1272 /// assert_eq!(iter.next(), Some(1));
1273 /// assert_eq!(iter.next(), Some(2));
1274 /// assert_eq!(iter.next(), None);
1277 /// If less than `n` elements are available,
1278 /// `take` will limit itself to the size of the underlying iterator:
1281 /// let v = vec![1, 2];
1282 /// let mut iter = v.into_iter().take(5);
1283 /// assert_eq!(iter.next(), Some(1));
1284 /// assert_eq!(iter.next(), Some(2));
1285 /// assert_eq!(iter.next(), None);
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 fn take(self, n: usize) -> Take<Self>
1296 /// An iterator adapter similar to [`fold`] that holds internal state and
1297 /// produces a new iterator.
1299 /// [`fold`]: Iterator::fold
1301 /// `scan()` takes two arguments: an initial value which seeds the internal
1302 /// state, and a closure with two arguments, the first being a mutable
1303 /// reference to the internal state and the second an iterator element.
1304 /// The closure can assign to the internal state to share state between
1307 /// On iteration, the closure will be applied to each element of the
1308 /// iterator and the return value from the closure, an [`Option`], is
1309 /// yielded by the iterator.
1316 /// let a = [1, 2, 3];
1318 /// let mut iter = a.iter().scan(1, |state, &x| {
1319 /// // each iteration, we'll multiply the state by the element
1320 /// *state = *state * x;
1322 /// // then, we'll yield the negation of the state
1326 /// assert_eq!(iter.next(), Some(-1));
1327 /// assert_eq!(iter.next(), Some(-2));
1328 /// assert_eq!(iter.next(), Some(-6));
1329 /// assert_eq!(iter.next(), None);
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1336 F: FnMut(&mut St, Self::Item) -> Option<B>,
1338 Scan::new(self, initial_state, f)
1341 /// Creates an iterator that works like map, but flattens nested structure.
1343 /// The [`map`] adapter is very useful, but only when the closure
1344 /// argument produces values. If it produces an iterator instead, there's
1345 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1348 /// You can think of `flat_map(f)` as the semantic equivalent
1349 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1351 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1352 /// one item for each element, and `flat_map()`'s closure returns an
1353 /// iterator for each element.
1355 /// [`map`]: Iterator::map
1356 /// [`flatten`]: Iterator::flatten
1363 /// let words = ["alpha", "beta", "gamma"];
1365 /// // chars() returns an iterator
1366 /// let merged: String = words.iter()
1367 /// .flat_map(|s| s.chars())
1369 /// assert_eq!(merged, "alphabetagamma");
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1377 F: FnMut(Self::Item) -> U,
1379 FlatMap::new(self, f)
1382 /// Creates an iterator that flattens nested structure.
1384 /// This is useful when you have an iterator of iterators or an iterator of
1385 /// things that can be turned into iterators and you want to remove one
1386 /// level of indirection.
1393 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1394 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1395 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1398 /// Mapping and then flattening:
1401 /// let words = ["alpha", "beta", "gamma"];
1403 /// // chars() returns an iterator
1404 /// let merged: String = words.iter()
1405 /// .map(|s| s.chars())
1408 /// assert_eq!(merged, "alphabetagamma");
1411 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1412 /// in this case since it conveys intent more clearly:
1415 /// let words = ["alpha", "beta", "gamma"];
1417 /// // chars() returns an iterator
1418 /// let merged: String = words.iter()
1419 /// .flat_map(|s| s.chars())
1421 /// assert_eq!(merged, "alphabetagamma");
1424 /// Flattening only removes one level of nesting at a time:
1427 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1429 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1430 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1432 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1433 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1436 /// Here we see that `flatten()` does not perform a "deep" flatten.
1437 /// Instead, only one level of nesting is removed. That is, if you
1438 /// `flatten()` a three-dimensional array, the result will be
1439 /// two-dimensional and not one-dimensional. To get a one-dimensional
1440 /// structure, you have to `flatten()` again.
1442 /// [`flat_map()`]: Iterator::flat_map
1444 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1445 fn flatten(self) -> Flatten<Self>
1448 Self::Item: IntoIterator,
1453 /// Creates an iterator which ends after the first [`None`].
1455 /// After an iterator returns [`None`], future calls may or may not yield
1456 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1457 /// [`None`] is given, it will always return [`None`] forever.
1459 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1460 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1461 /// if the [`FusedIterator`] trait is improperly implemented.
1463 /// [`Some(T)`]: Some
1464 /// [`FusedIterator`]: crate::iter::FusedIterator
1471 /// // an iterator which alternates between Some and None
1472 /// struct Alternate {
1476 /// impl Iterator for Alternate {
1477 /// type Item = i32;
1479 /// fn next(&mut self) -> Option<i32> {
1480 /// let val = self.state;
1481 /// self.state = self.state + 1;
1483 /// // if it's even, Some(i32), else None
1484 /// if val % 2 == 0 {
1492 /// let mut iter = Alternate { state: 0 };
1494 /// // we can see our iterator going back and forth
1495 /// assert_eq!(iter.next(), Some(0));
1496 /// assert_eq!(iter.next(), None);
1497 /// assert_eq!(iter.next(), Some(2));
1498 /// assert_eq!(iter.next(), None);
1500 /// // however, once we fuse it...
1501 /// let mut iter = iter.fuse();
1503 /// assert_eq!(iter.next(), Some(4));
1504 /// assert_eq!(iter.next(), None);
1506 /// // it will always return `None` after the first time.
1507 /// assert_eq!(iter.next(), None);
1508 /// assert_eq!(iter.next(), None);
1509 /// assert_eq!(iter.next(), None);
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 fn fuse(self) -> Fuse<Self>
1520 /// Does something with each element of an iterator, passing the value on.
1522 /// When using iterators, you'll often chain several of them together.
1523 /// While working on such code, you might want to check out what's
1524 /// happening at various parts in the pipeline. To do that, insert
1525 /// a call to `inspect()`.
1527 /// It's more common for `inspect()` to be used as a debugging tool than to
1528 /// exist in your final code, but applications may find it useful in certain
1529 /// situations when errors need to be logged before being discarded.
1536 /// let a = [1, 4, 2, 3];
1538 /// // this iterator sequence is complex.
1539 /// let sum = a.iter()
1541 /// .filter(|x| x % 2 == 0)
1542 /// .fold(0, |sum, i| sum + i);
1544 /// println!("{}", sum);
1546 /// // let's add some inspect() calls to investigate what's happening
1547 /// let sum = a.iter()
1549 /// .inspect(|x| println!("about to filter: {}", x))
1550 /// .filter(|x| x % 2 == 0)
1551 /// .inspect(|x| println!("made it through filter: {}", x))
1552 /// .fold(0, |sum, i| sum + i);
1554 /// println!("{}", sum);
1557 /// This will print:
1561 /// about to filter: 1
1562 /// about to filter: 4
1563 /// made it through filter: 4
1564 /// about to filter: 2
1565 /// made it through filter: 2
1566 /// about to filter: 3
1570 /// Logging errors before discarding them:
1573 /// let lines = ["1", "2", "a"];
1575 /// let sum: i32 = lines
1577 /// .map(|line| line.parse::<i32>())
1578 /// .inspect(|num| {
1579 /// if let Err(ref e) = *num {
1580 /// println!("Parsing error: {}", e);
1583 /// .filter_map(Result::ok)
1586 /// println!("Sum: {}", sum);
1589 /// This will print:
1592 /// Parsing error: invalid digit found in string
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1600 F: FnMut(&Self::Item),
1602 Inspect::new(self, f)
1605 /// Borrows an iterator, rather than consuming it.
1607 /// This is useful to allow applying iterator adapters while still
1608 /// retaining ownership of the original iterator.
1615 /// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
1617 /// // Take the first two words.
1618 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1619 /// assert_eq!(hello_world, vec!["hello", "world"]);
1621 /// // Collect the rest of the words.
1622 /// // We can only do this because we used `by_ref` earlier.
1623 /// let of_rust: Vec<_> = words.collect();
1624 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 fn by_ref(&mut self) -> &mut Self
1634 /// Transforms an iterator into a collection.
1636 /// `collect()` can take anything iterable, and turn it into a relevant
1637 /// collection. This is one of the more powerful methods in the standard
1638 /// library, used in a variety of contexts.
1640 /// The most basic pattern in which `collect()` is used is to turn one
1641 /// collection into another. You take a collection, call [`iter`] on it,
1642 /// do a bunch of transformations, and then `collect()` at the end.
1644 /// `collect()` can also create instances of types that are not typical
1645 /// collections. For example, a [`String`] can be built from [`char`]s,
1646 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1647 /// into `Result<Collection<T>, E>`. See the examples below for more.
1649 /// Because `collect()` is so general, it can cause problems with type
1650 /// inference. As such, `collect()` is one of the few times you'll see
1651 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1652 /// helps the inference algorithm understand specifically which collection
1653 /// you're trying to collect into.
1660 /// let a = [1, 2, 3];
1662 /// let doubled: Vec<i32> = a.iter()
1663 /// .map(|&x| x * 2)
1666 /// assert_eq!(vec![2, 4, 6], doubled);
1669 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1670 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1672 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1675 /// use std::collections::VecDeque;
1677 /// let a = [1, 2, 3];
1679 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1681 /// assert_eq!(2, doubled[0]);
1682 /// assert_eq!(4, doubled[1]);
1683 /// assert_eq!(6, doubled[2]);
1686 /// Using the 'turbofish' instead of annotating `doubled`:
1689 /// let a = [1, 2, 3];
1691 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1693 /// assert_eq!(vec![2, 4, 6], doubled);
1696 /// Because `collect()` only cares about what you're collecting into, you can
1697 /// still use a partial type hint, `_`, with the turbofish:
1700 /// let a = [1, 2, 3];
1702 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1704 /// assert_eq!(vec![2, 4, 6], doubled);
1707 /// Using `collect()` to make a [`String`]:
1710 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1712 /// let hello: String = chars.iter()
1713 /// .map(|&x| x as u8)
1714 /// .map(|x| (x + 1) as char)
1717 /// assert_eq!("hello", hello);
1720 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1721 /// see if any of them failed:
1724 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1726 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1728 /// // gives us the first error
1729 /// assert_eq!(Err("nope"), result);
1731 /// let results = [Ok(1), Ok(3)];
1733 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1735 /// // gives us the list of answers
1736 /// assert_eq!(Ok(vec![1, 3]), result);
1739 /// [`iter`]: Iterator::next
1740 /// [`String`]: ../../std/string/struct.String.html
1741 /// [`char`]: type@char
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1745 fn collect<B: FromIterator<Self::Item>>(self) -> B
1749 FromIterator::from_iter(self)
1752 /// Consumes an iterator, creating two collections from it.
1754 /// The predicate passed to `partition()` can return `true`, or `false`.
1755 /// `partition()` returns a pair, all of the elements for which it returned
1756 /// `true`, and all of the elements for which it returned `false`.
1758 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1760 /// [`is_partitioned()`]: Iterator::is_partitioned
1761 /// [`partition_in_place()`]: Iterator::partition_in_place
1768 /// let a = [1, 2, 3];
1770 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1772 /// .partition(|&n| n % 2 == 0);
1774 /// assert_eq!(even, vec![2]);
1775 /// assert_eq!(odd, vec![1, 3]);
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 fn partition<B, F>(self, f: F) -> (B, B)
1781 B: Default + Extend<Self::Item>,
1782 F: FnMut(&Self::Item) -> bool,
1785 fn extend<'a, T, B: Extend<T>>(
1786 mut f: impl FnMut(&T) -> bool + 'a,
1789 ) -> impl FnMut((), T) + 'a {
1794 right.extend_one(x);
1799 let mut left: B = Default::default();
1800 let mut right: B = Default::default();
1802 self.fold((), extend(f, &mut left, &mut right));
1807 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1808 /// such that all those that return `true` precede all those that return `false`.
1809 /// Returns the number of `true` elements found.
1811 /// The relative order of partitioned items is not maintained.
1813 /// # Current implementation
1814 /// Current algorithms tries finding the first element for which the predicate evaluates
1815 /// to false, and the last element for which it evaluates to true and repeatedly swaps them.
1817 /// Time Complexity: *O*(*N*)
1819 /// See also [`is_partitioned()`] and [`partition()`].
1821 /// [`is_partitioned()`]: Iterator::is_partitioned
1822 /// [`partition()`]: Iterator::partition
1827 /// #![feature(iter_partition_in_place)]
1829 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1831 /// // Partition in-place between evens and odds
1832 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1834 /// assert_eq!(i, 3);
1835 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1836 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1838 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1839 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1841 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1842 P: FnMut(&T) -> bool,
1844 // FIXME: should we worry about the count overflowing? The only way to have more than
1845 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1847 // These closure "factory" functions exist to avoid genericity in `Self`.
1851 predicate: &'a mut impl FnMut(&T) -> bool,
1852 true_count: &'a mut usize,
1853 ) -> impl FnMut(&&mut T) -> bool + 'a {
1855 let p = predicate(&**x);
1856 *true_count += p as usize;
1862 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1863 move |x| predicate(&**x)
1866 // Repeatedly find the first `false` and swap it with the last `true`.
1867 let mut true_count = 0;
1868 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1869 if let Some(tail) = self.rfind(is_true(predicate)) {
1870 crate::mem::swap(head, tail);
1879 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1880 /// such that all those that return `true` precede all those that return `false`.
1882 /// See also [`partition()`] and [`partition_in_place()`].
1884 /// [`partition()`]: Iterator::partition
1885 /// [`partition_in_place()`]: Iterator::partition_in_place
1890 /// #![feature(iter_is_partitioned)]
1892 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1893 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1895 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1896 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1899 P: FnMut(Self::Item) -> bool,
1901 // Either all items test `true`, or the first clause stops at `false`
1902 // and we check that there are no more `true` items after that.
1903 self.all(&mut predicate) || !self.any(predicate)
1906 /// An iterator method that applies a function as long as it returns
1907 /// successfully, producing a single, final value.
1909 /// `try_fold()` takes two arguments: an initial value, and a closure with
1910 /// two arguments: an 'accumulator', and an element. The closure either
1911 /// returns successfully, with the value that the accumulator should have
1912 /// for the next iteration, or it returns failure, with an error value that
1913 /// is propagated back to the caller immediately (short-circuiting).
1915 /// The initial value is the value the accumulator will have on the first
1916 /// call. If applying the closure succeeded against every element of the
1917 /// iterator, `try_fold()` returns the final accumulator as success.
1919 /// Folding is useful whenever you have a collection of something, and want
1920 /// to produce a single value from it.
1922 /// # Note to Implementors
1924 /// Several of the other (forward) methods have default implementations in
1925 /// terms of this one, so try to implement this explicitly if it can
1926 /// do something better than the default `for` loop implementation.
1928 /// In particular, try to have this call `try_fold()` on the internal parts
1929 /// from which this iterator is composed. If multiple calls are needed,
1930 /// the `?` operator may be convenient for chaining the accumulator value
1931 /// along, but beware any invariants that need to be upheld before those
1932 /// early returns. This is a `&mut self` method, so iteration needs to be
1933 /// resumable after hitting an error here.
1940 /// let a = [1, 2, 3];
1942 /// // the checked sum of all of the elements of the array
1943 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1945 /// assert_eq!(sum, Some(6));
1948 /// Short-circuiting:
1951 /// let a = [10, 20, 30, 100, 40, 50];
1952 /// let mut it = a.iter();
1954 /// // This sum overflows when adding the 100 element
1955 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1956 /// assert_eq!(sum, None);
1958 /// // Because it short-circuited, the remaining elements are still
1959 /// // available through the iterator.
1960 /// assert_eq!(it.len(), 2);
1961 /// assert_eq!(it.next(), Some(&40));
1964 /// While you cannot `break` from a closure, the [`crate::ops::ControlFlow`]
1965 /// type allows a similar idea:
1968 /// use std::ops::ControlFlow;
1970 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
1971 /// if let Some(next) = prev.checked_add(x) {
1972 /// ControlFlow::Continue(next)
1974 /// ControlFlow::Break(prev)
1977 /// assert_eq!(triangular, ControlFlow::Break(120));
1979 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
1980 /// if let Some(next) = prev.checked_add(x) {
1981 /// ControlFlow::Continue(next)
1983 /// ControlFlow::Break(prev)
1986 /// assert_eq!(triangular, ControlFlow::Continue(435));
1989 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1990 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1993 F: FnMut(B, Self::Item) -> R,
1996 let mut accum = init;
1997 while let Some(x) = self.next() {
1998 accum = f(accum, x)?;
2003 /// An iterator method that applies a fallible function to each item in the
2004 /// iterator, stopping at the first error and returning that error.
2006 /// This can also be thought of as the fallible form of [`for_each()`]
2007 /// or as the stateless version of [`try_fold()`].
2009 /// [`for_each()`]: Iterator::for_each
2010 /// [`try_fold()`]: Iterator::try_fold
2015 /// use std::fs::rename;
2016 /// use std::io::{stdout, Write};
2017 /// use std::path::Path;
2019 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2021 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
2022 /// assert!(res.is_ok());
2024 /// let mut it = data.iter().cloned();
2025 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2026 /// assert!(res.is_err());
2027 /// // It short-circuited, so the remaining items are still in the iterator:
2028 /// assert_eq!(it.next(), Some("stale_bread.json"));
2031 /// The [`crate::ops::ControlFlow`] type can be used with this method for the
2032 /// situations in which you'd use `break` and `continue` in a normal loop:
2035 /// use std::ops::ControlFlow;
2037 /// let r = (2..100).try_for_each(|x| {
2038 /// if 323 % x == 0 {
2039 /// return ControlFlow::Break(x)
2042 /// ControlFlow::Continue(())
2044 /// assert_eq!(r, ControlFlow::Break(17));
2047 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2048 fn try_for_each<F, R>(&mut self, f: F) -> R
2051 F: FnMut(Self::Item) -> R,
2052 R: Try<Output = ()>,
2055 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2059 self.try_fold((), call(f))
2062 /// Folds every element into an accumulator by applying an operation,
2063 /// returning the final result.
2065 /// `fold()` takes two arguments: an initial value, and a closure with two
2066 /// arguments: an 'accumulator', and an element. The closure returns the value that
2067 /// the accumulator should have for the next iteration.
2069 /// The initial value is the value the accumulator will have on the first
2072 /// After applying this closure to every element of the iterator, `fold()`
2073 /// returns the accumulator.
2075 /// This operation is sometimes called 'reduce' or 'inject'.
2077 /// Folding is useful whenever you have a collection of something, and want
2078 /// to produce a single value from it.
2080 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2081 /// might not terminate for infinite iterators, even on traits for which a
2082 /// result is determinable in finite time.
2084 /// Note: [`reduce()`] can be used to use the first element as the initial
2085 /// value, if the accumulator type and item type is the same.
2087 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2088 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2089 /// operators like `-` the order will affect the final result.
2090 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2092 /// # Note to Implementors
2094 /// Several of the other (forward) methods have default implementations in
2095 /// terms of this one, so try to implement this explicitly if it can
2096 /// do something better than the default `for` loop implementation.
2098 /// In particular, try to have this call `fold()` on the internal parts
2099 /// from which this iterator is composed.
2106 /// let a = [1, 2, 3];
2108 /// // the sum of all of the elements of the array
2109 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2111 /// assert_eq!(sum, 6);
2114 /// Let's walk through each step of the iteration here:
2116 /// | element | acc | x | result |
2117 /// |---------|-----|---|--------|
2119 /// | 1 | 0 | 1 | 1 |
2120 /// | 2 | 1 | 2 | 3 |
2121 /// | 3 | 3 | 3 | 6 |
2123 /// And so, our final result, `6`.
2125 /// This example demonstrates the left-associative nature of `fold()`:
2126 /// it builds a string, starting with an initial value
2127 /// and continuing with each element from the front until the back:
2130 /// let numbers = [1, 2, 3, 4, 5];
2132 /// let zero = "0".to_string();
2134 /// let result = numbers.iter().fold(zero, |acc, &x| {
2135 /// format!("({} + {})", acc, x)
2138 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2140 /// It's common for people who haven't used iterators a lot to
2141 /// use a `for` loop with a list of things to build up a result. Those
2142 /// can be turned into `fold()`s:
2144 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2147 /// let numbers = [1, 2, 3, 4, 5];
2149 /// let mut result = 0;
2152 /// for i in &numbers {
2153 /// result = result + i;
2157 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2159 /// // they're the same
2160 /// assert_eq!(result, result2);
2163 /// [`reduce()`]: Iterator::reduce
2164 #[doc(alias = "inject", alias = "foldl")]
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2170 F: FnMut(B, Self::Item) -> B,
2172 let mut accum = init;
2173 while let Some(x) = self.next() {
2174 accum = f(accum, x);
2179 /// Reduces the elements to a single one, by repeatedly applying a reducing
2182 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2183 /// result of the reduction.
2185 /// For iterators with at least one element, this is the same as [`fold()`]
2186 /// with the first element of the iterator as the initial value, folding
2187 /// every subsequent element into it.
2189 /// [`fold()`]: Iterator::fold
2193 /// Find the maximum value:
2196 /// fn find_max<I>(iter: I) -> Option<I::Item>
2197 /// where I: Iterator,
2200 /// iter.reduce(|a, b| {
2201 /// if a >= b { a } else { b }
2204 /// let a = [10, 20, 5, -23, 0];
2205 /// let b: [u32; 0] = [];
2207 /// assert_eq!(find_max(a.iter()), Some(&20));
2208 /// assert_eq!(find_max(b.iter()), None);
2211 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2212 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2215 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2217 let first = self.next()?;
2218 Some(self.fold(first, f))
2221 /// Tests if every element of the iterator matches a predicate.
2223 /// `all()` takes a closure that returns `true` or `false`. It applies
2224 /// this closure to each element of the iterator, and if they all return
2225 /// `true`, then so does `all()`. If any of them return `false`, it
2226 /// returns `false`.
2228 /// `all()` is short-circuiting; in other words, it will stop processing
2229 /// as soon as it finds a `false`, given that no matter what else happens,
2230 /// the result will also be `false`.
2232 /// An empty iterator returns `true`.
2239 /// let a = [1, 2, 3];
2241 /// assert!(a.iter().all(|&x| x > 0));
2243 /// assert!(!a.iter().all(|&x| x > 2));
2246 /// Stopping at the first `false`:
2249 /// let a = [1, 2, 3];
2251 /// let mut iter = a.iter();
2253 /// assert!(!iter.all(|&x| x != 2));
2255 /// // we can still use `iter`, as there are more elements.
2256 /// assert_eq!(iter.next(), Some(&3));
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 fn all<F>(&mut self, f: F) -> bool
2263 F: FnMut(Self::Item) -> bool,
2266 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2268 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2271 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2274 /// Tests if any element of the iterator matches a predicate.
2276 /// `any()` takes a closure that returns `true` or `false`. It applies
2277 /// this closure to each element of the iterator, and if any of them return
2278 /// `true`, then so does `any()`. If they all return `false`, it
2279 /// returns `false`.
2281 /// `any()` is short-circuiting; in other words, it will stop processing
2282 /// as soon as it finds a `true`, given that no matter what else happens,
2283 /// the result will also be `true`.
2285 /// An empty iterator returns `false`.
2292 /// let a = [1, 2, 3];
2294 /// assert!(a.iter().any(|&x| x > 0));
2296 /// assert!(!a.iter().any(|&x| x > 5));
2299 /// Stopping at the first `true`:
2302 /// let a = [1, 2, 3];
2304 /// let mut iter = a.iter();
2306 /// assert!(iter.any(|&x| x != 2));
2308 /// // we can still use `iter`, as there are more elements.
2309 /// assert_eq!(iter.next(), Some(&2));
2312 #[stable(feature = "rust1", since = "1.0.0")]
2313 fn any<F>(&mut self, f: F) -> bool
2316 F: FnMut(Self::Item) -> bool,
2319 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2321 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2325 self.try_fold((), check(f)) == ControlFlow::BREAK
2328 /// Searches for an element of an iterator that satisfies a predicate.
2330 /// `find()` takes a closure that returns `true` or `false`. It applies
2331 /// this closure to each element of the iterator, and if any of them return
2332 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2333 /// `false`, it returns [`None`].
2335 /// `find()` is short-circuiting; in other words, it will stop processing
2336 /// as soon as the closure returns `true`.
2338 /// Because `find()` takes a reference, and many iterators iterate over
2339 /// references, this leads to a possibly confusing situation where the
2340 /// argument is a double reference. You can see this effect in the
2341 /// examples below, with `&&x`.
2343 /// [`Some(element)`]: Some
2350 /// let a = [1, 2, 3];
2352 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2354 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2357 /// Stopping at the first `true`:
2360 /// let a = [1, 2, 3];
2362 /// let mut iter = a.iter();
2364 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2366 /// // we can still use `iter`, as there are more elements.
2367 /// assert_eq!(iter.next(), Some(&3));
2370 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2372 #[stable(feature = "rust1", since = "1.0.0")]
2373 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2376 P: FnMut(&Self::Item) -> bool,
2379 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2381 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2385 self.try_fold((), check(predicate)).break_value()
2388 /// Applies function to the elements of iterator and returns
2389 /// the first non-none result.
2391 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2396 /// let a = ["lol", "NaN", "2", "5"];
2398 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2400 /// assert_eq!(first_number, Some(2));
2403 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2404 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2407 F: FnMut(Self::Item) -> Option<B>,
2410 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2411 move |(), x| match f(x) {
2412 Some(x) => ControlFlow::Break(x),
2413 None => ControlFlow::CONTINUE,
2417 self.try_fold((), check(f)).break_value()
2420 /// Applies function to the elements of iterator and returns
2421 /// the first true result or the first error.
2426 /// #![feature(try_find)]
2428 /// let a = ["1", "2", "lol", "NaN", "5"];
2430 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2431 /// Ok(s.parse::<i32>()? == search)
2434 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2435 /// assert_eq!(result, Ok(Some(&"2")));
2437 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2438 /// assert!(result.is_err());
2441 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2442 fn try_find<F, R, E>(&mut self, f: F) -> Result<Option<Self::Item>, E>
2445 F: FnMut(&Self::Item) -> R,
2446 R: Try<Output = bool>,
2447 // FIXME: This bound is rather strange, but means minimal breakage on nightly.
2448 // See #85115 for the issue tracking a holistic solution for this and try_map.
2449 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2452 fn check<F, T, R, E>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, E>>
2455 R: Try<Output = bool>,
2456 R: crate::ops::TryV2<Residual = Result<crate::convert::Infallible, E>>,
2458 move |(), x| match f(&x).branch() {
2459 ControlFlow::Continue(false) => ControlFlow::CONTINUE,
2460 ControlFlow::Continue(true) => ControlFlow::Break(Ok(x)),
2461 ControlFlow::Break(Err(x)) => ControlFlow::Break(Err(x)),
2465 self.try_fold((), check(f)).break_value().transpose()
2468 /// Searches for an element in an iterator, returning its index.
2470 /// `position()` takes a closure that returns `true` or `false`. It applies
2471 /// this closure to each element of the iterator, and if one of them
2472 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2473 /// them return `false`, it returns [`None`].
2475 /// `position()` is short-circuiting; in other words, it will stop
2476 /// processing as soon as it finds a `true`.
2478 /// # Overflow Behavior
2480 /// The method does no guarding against overflows, so if there are more
2481 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2482 /// result or panics. If debug assertions are enabled, a panic is
2487 /// This function might panic if the iterator has more than `usize::MAX`
2488 /// non-matching elements.
2490 /// [`Some(index)`]: Some
2497 /// let a = [1, 2, 3];
2499 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2501 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2504 /// Stopping at the first `true`:
2507 /// let a = [1, 2, 3, 4];
2509 /// let mut iter = a.iter();
2511 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2513 /// // we can still use `iter`, as there are more elements.
2514 /// assert_eq!(iter.next(), Some(&3));
2516 /// // The returned index depends on iterator state
2517 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 fn position<P>(&mut self, predicate: P) -> Option<usize>
2525 P: FnMut(Self::Item) -> bool,
2529 mut predicate: impl FnMut(T) -> bool,
2530 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2531 #[rustc_inherit_overflow_checks]
2533 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2537 self.try_fold(0, check(predicate)).break_value()
2540 /// Searches for an element in an iterator from the right, returning its
2543 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2544 /// this closure to each element of the iterator, starting from the end,
2545 /// and if one of them returns `true`, then `rposition()` returns
2546 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2548 /// `rposition()` is short-circuiting; in other words, it will stop
2549 /// processing as soon as it finds a `true`.
2551 /// [`Some(index)`]: Some
2558 /// let a = [1, 2, 3];
2560 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2562 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2565 /// Stopping at the first `true`:
2568 /// let a = [1, 2, 3];
2570 /// let mut iter = a.iter();
2572 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2574 /// // we can still use `iter`, as there are more elements.
2575 /// assert_eq!(iter.next(), Some(&1));
2578 #[stable(feature = "rust1", since = "1.0.0")]
2579 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2581 P: FnMut(Self::Item) -> bool,
2582 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2584 // No need for an overflow check here, because `ExactSizeIterator`
2585 // implies that the number of elements fits into a `usize`.
2588 mut predicate: impl FnMut(T) -> bool,
2589 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2592 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2597 self.try_rfold(n, check(predicate)).break_value()
2600 /// Returns the maximum element of an iterator.
2602 /// If several elements are equally maximum, the last element is
2603 /// returned. If the iterator is empty, [`None`] is returned.
2605 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2606 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2609 /// vec![2.4, f32::NAN, 1.3]
2611 /// .reduce(f32::max)
2622 /// let a = [1, 2, 3];
2623 /// let b: Vec<u32> = Vec::new();
2625 /// assert_eq!(a.iter().max(), Some(&3));
2626 /// assert_eq!(b.iter().max(), None);
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 fn max(self) -> Option<Self::Item>
2635 self.max_by(Ord::cmp)
2638 /// Returns the minimum element of an iterator.
2640 /// If several elements are equally minimum, the first element is returned.
2641 /// If the iterator is empty, [`None`] is returned.
2643 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2644 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2647 /// vec![2.4, f32::NAN, 1.3]
2649 /// .reduce(f32::min)
2660 /// let a = [1, 2, 3];
2661 /// let b: Vec<u32> = Vec::new();
2663 /// assert_eq!(a.iter().min(), Some(&1));
2664 /// assert_eq!(b.iter().min(), None);
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 fn min(self) -> Option<Self::Item>
2673 self.min_by(Ord::cmp)
2676 /// Returns the element that gives the maximum value from the
2677 /// specified function.
2679 /// If several elements are equally maximum, the last element is
2680 /// returned. If the iterator is empty, [`None`] is returned.
2685 /// let a = [-3_i32, 0, 1, 5, -10];
2686 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2689 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2690 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2693 F: FnMut(&Self::Item) -> B,
2696 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2701 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2705 let (_, x) = self.map(key(f)).max_by(compare)?;
2709 /// Returns the element that gives the maximum value with respect to the
2710 /// specified comparison function.
2712 /// If several elements are equally maximum, the last element is
2713 /// returned. If the iterator is empty, [`None`] is returned.
2718 /// let a = [-3_i32, 0, 1, 5, -10];
2719 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2722 #[stable(feature = "iter_max_by", since = "1.15.0")]
2723 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2726 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2729 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2730 move |x, y| cmp::max_by(x, y, &mut compare)
2733 self.reduce(fold(compare))
2736 /// Returns the element that gives the minimum value from the
2737 /// specified function.
2739 /// If several elements are equally minimum, the first element is
2740 /// returned. If the iterator is empty, [`None`] is returned.
2745 /// let a = [-3_i32, 0, 1, 5, -10];
2746 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2749 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2750 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2753 F: FnMut(&Self::Item) -> B,
2756 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2761 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2765 let (_, x) = self.map(key(f)).min_by(compare)?;
2769 /// Returns the element that gives the minimum value with respect to the
2770 /// specified comparison function.
2772 /// If several elements are equally minimum, the first element is
2773 /// returned. If the iterator is empty, [`None`] is returned.
2778 /// let a = [-3_i32, 0, 1, 5, -10];
2779 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2782 #[stable(feature = "iter_min_by", since = "1.15.0")]
2783 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2786 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2789 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2790 move |x, y| cmp::min_by(x, y, &mut compare)
2793 self.reduce(fold(compare))
2796 /// Reverses an iterator's direction.
2798 /// Usually, iterators iterate from left to right. After using `rev()`,
2799 /// an iterator will instead iterate from right to left.
2801 /// This is only possible if the iterator has an end, so `rev()` only
2802 /// works on [`DoubleEndedIterator`]s.
2807 /// let a = [1, 2, 3];
2809 /// let mut iter = a.iter().rev();
2811 /// assert_eq!(iter.next(), Some(&3));
2812 /// assert_eq!(iter.next(), Some(&2));
2813 /// assert_eq!(iter.next(), Some(&1));
2815 /// assert_eq!(iter.next(), None);
2818 #[doc(alias = "reverse")]
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 fn rev(self) -> Rev<Self>
2822 Self: Sized + DoubleEndedIterator,
2827 /// Converts an iterator of pairs into a pair of containers.
2829 /// `unzip()` consumes an entire iterator of pairs, producing two
2830 /// collections: one from the left elements of the pairs, and one
2831 /// from the right elements.
2833 /// This function is, in some sense, the opposite of [`zip`].
2835 /// [`zip`]: Iterator::zip
2842 /// let a = [(1, 2), (3, 4)];
2844 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2846 /// assert_eq!(left, [1, 3]);
2847 /// assert_eq!(right, [2, 4]);
2849 #[stable(feature = "rust1", since = "1.0.0")]
2850 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2852 FromA: Default + Extend<A>,
2853 FromB: Default + Extend<B>,
2854 Self: Sized + Iterator<Item = (A, B)>,
2856 fn extend<'a, A, B>(
2857 ts: &'a mut impl Extend<A>,
2858 us: &'a mut impl Extend<B>,
2859 ) -> impl FnMut((), (A, B)) + 'a {
2866 let mut ts: FromA = Default::default();
2867 let mut us: FromB = Default::default();
2869 let (lower_bound, _) = self.size_hint();
2870 if lower_bound > 0 {
2871 ts.extend_reserve(lower_bound);
2872 us.extend_reserve(lower_bound);
2875 self.fold((), extend(&mut ts, &mut us));
2880 /// Creates an iterator which copies all of its elements.
2882 /// This is useful when you have an iterator over `&T`, but you need an
2883 /// iterator over `T`.
2890 /// let a = [1, 2, 3];
2892 /// let v_copied: Vec<_> = a.iter().copied().collect();
2894 /// // copied is the same as .map(|&x| x)
2895 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2897 /// assert_eq!(v_copied, vec![1, 2, 3]);
2898 /// assert_eq!(v_map, vec![1, 2, 3]);
2900 #[stable(feature = "iter_copied", since = "1.36.0")]
2901 fn copied<'a, T: 'a>(self) -> Copied<Self>
2903 Self: Sized + Iterator<Item = &'a T>,
2909 /// Creates an iterator which [`clone`]s all of its elements.
2911 /// This is useful when you have an iterator over `&T`, but you need an
2912 /// iterator over `T`.
2914 /// [`clone`]: Clone::clone
2921 /// let a = [1, 2, 3];
2923 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2925 /// // cloned is the same as .map(|&x| x), for integers
2926 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2928 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2929 /// assert_eq!(v_map, vec![1, 2, 3]);
2931 #[stable(feature = "rust1", since = "1.0.0")]
2932 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2934 Self: Sized + Iterator<Item = &'a T>,
2940 /// Repeats an iterator endlessly.
2942 /// Instead of stopping at [`None`], the iterator will instead start again,
2943 /// from the beginning. After iterating again, it will start at the
2944 /// beginning again. And again. And again. Forever.
2951 /// let a = [1, 2, 3];
2953 /// let mut it = a.iter().cycle();
2955 /// assert_eq!(it.next(), Some(&1));
2956 /// assert_eq!(it.next(), Some(&2));
2957 /// assert_eq!(it.next(), Some(&3));
2958 /// assert_eq!(it.next(), Some(&1));
2959 /// assert_eq!(it.next(), Some(&2));
2960 /// assert_eq!(it.next(), Some(&3));
2961 /// assert_eq!(it.next(), Some(&1));
2963 #[stable(feature = "rust1", since = "1.0.0")]
2965 fn cycle(self) -> Cycle<Self>
2967 Self: Sized + Clone,
2972 /// Sums the elements of an iterator.
2974 /// Takes each element, adds them together, and returns the result.
2976 /// An empty iterator returns the zero value of the type.
2980 /// When calling `sum()` and a primitive integer type is being returned, this
2981 /// method will panic if the computation overflows and debug assertions are
2989 /// let a = [1, 2, 3];
2990 /// let sum: i32 = a.iter().sum();
2992 /// assert_eq!(sum, 6);
2994 #[stable(feature = "iter_arith", since = "1.11.0")]
2995 fn sum<S>(self) -> S
3003 /// Iterates over the entire iterator, multiplying all the elements
3005 /// An empty iterator returns the one value of the type.
3009 /// When calling `product()` and a primitive integer type is being returned,
3010 /// method will panic if the computation overflows and debug assertions are
3016 /// fn factorial(n: u32) -> u32 {
3017 /// (1..=n).product()
3019 /// assert_eq!(factorial(0), 1);
3020 /// assert_eq!(factorial(1), 1);
3021 /// assert_eq!(factorial(5), 120);
3023 #[stable(feature = "iter_arith", since = "1.11.0")]
3024 fn product<P>(self) -> P
3027 P: Product<Self::Item>,
3029 Product::product(self)
3032 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3038 /// use std::cmp::Ordering;
3040 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3041 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3042 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3044 #[stable(feature = "iter_order", since = "1.5.0")]
3045 fn cmp<I>(self, other: I) -> Ordering
3047 I: IntoIterator<Item = Self::Item>,
3051 self.cmp_by(other, |x, y| x.cmp(&y))
3054 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3055 /// of another with respect to the specified comparison function.
3062 /// #![feature(iter_order_by)]
3064 /// use std::cmp::Ordering;
3066 /// let xs = [1, 2, 3, 4];
3067 /// let ys = [1, 4, 9, 16];
3069 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3070 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3071 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3073 #[unstable(feature = "iter_order_by", issue = "64295")]
3074 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
3078 F: FnMut(Self::Item, I::Item) -> Ordering,
3080 let mut other = other.into_iter();
3083 let x = match self.next() {
3085 if other.next().is_none() {
3086 return Ordering::Equal;
3088 return Ordering::Less;
3094 let y = match other.next() {
3095 None => return Ordering::Greater,
3100 Ordering::Equal => (),
3101 non_eq => return non_eq,
3106 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3112 /// use std::cmp::Ordering;
3114 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3115 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3116 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3118 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3120 #[stable(feature = "iter_order", since = "1.5.0")]
3121 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3124 Self::Item: PartialOrd<I::Item>,
3127 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3130 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3131 /// of another with respect to the specified comparison function.
3138 /// #![feature(iter_order_by)]
3140 /// use std::cmp::Ordering;
3142 /// let xs = [1.0, 2.0, 3.0, 4.0];
3143 /// let ys = [1.0, 4.0, 9.0, 16.0];
3146 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3147 /// Some(Ordering::Less)
3150 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3151 /// Some(Ordering::Equal)
3154 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3155 /// Some(Ordering::Greater)
3158 #[unstable(feature = "iter_order_by", issue = "64295")]
3159 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3163 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3165 let mut other = other.into_iter();
3168 let x = match self.next() {
3170 if other.next().is_none() {
3171 return Some(Ordering::Equal);
3173 return Some(Ordering::Less);
3179 let y = match other.next() {
3180 None => return Some(Ordering::Greater),
3184 match partial_cmp(x, y) {
3185 Some(Ordering::Equal) => (),
3186 non_eq => return non_eq,
3191 /// Determines if the elements of this [`Iterator`] are equal to those of
3197 /// assert_eq!([1].iter().eq([1].iter()), true);
3198 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3200 #[stable(feature = "iter_order", since = "1.5.0")]
3201 fn eq<I>(self, other: I) -> bool
3204 Self::Item: PartialEq<I::Item>,
3207 self.eq_by(other, |x, y| x == y)
3210 /// Determines if the elements of this [`Iterator`] are equal to those of
3211 /// another with respect to the specified equality function.
3218 /// #![feature(iter_order_by)]
3220 /// let xs = [1, 2, 3, 4];
3221 /// let ys = [1, 4, 9, 16];
3223 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3225 #[unstable(feature = "iter_order_by", issue = "64295")]
3226 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3230 F: FnMut(Self::Item, I::Item) -> bool,
3232 let mut other = other.into_iter();
3235 let x = match self.next() {
3236 None => return other.next().is_none(),
3240 let y = match other.next() {
3241 None => return false,
3251 /// Determines if the elements of this [`Iterator`] are unequal to those of
3257 /// assert_eq!([1].iter().ne([1].iter()), false);
3258 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3260 #[stable(feature = "iter_order", since = "1.5.0")]
3261 fn ne<I>(self, other: I) -> bool
3264 Self::Item: PartialEq<I::Item>,
3270 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3271 /// less than those of another.
3276 /// assert_eq!([1].iter().lt([1].iter()), false);
3277 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3278 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3279 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3281 #[stable(feature = "iter_order", since = "1.5.0")]
3282 fn lt<I>(self, other: I) -> bool
3285 Self::Item: PartialOrd<I::Item>,
3288 self.partial_cmp(other) == Some(Ordering::Less)
3291 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3292 /// less or equal to those of another.
3297 /// assert_eq!([1].iter().le([1].iter()), true);
3298 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3299 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3300 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3302 #[stable(feature = "iter_order", since = "1.5.0")]
3303 fn le<I>(self, other: I) -> bool
3306 Self::Item: PartialOrd<I::Item>,
3309 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3312 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3313 /// greater than those of another.
3318 /// assert_eq!([1].iter().gt([1].iter()), false);
3319 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3320 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3321 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3323 #[stable(feature = "iter_order", since = "1.5.0")]
3324 fn gt<I>(self, other: I) -> bool
3327 Self::Item: PartialOrd<I::Item>,
3330 self.partial_cmp(other) == Some(Ordering::Greater)
3333 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3334 /// greater than or equal to those of another.
3339 /// assert_eq!([1].iter().ge([1].iter()), true);
3340 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3341 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3342 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3344 #[stable(feature = "iter_order", since = "1.5.0")]
3345 fn ge<I>(self, other: I) -> bool
3348 Self::Item: PartialOrd<I::Item>,
3351 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3354 /// Checks if the elements of this iterator are sorted.
3356 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3357 /// iterator yields exactly zero or one element, `true` is returned.
3359 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3360 /// implies that this function returns `false` if any two consecutive items are not
3366 /// #![feature(is_sorted)]
3368 /// assert!([1, 2, 2, 9].iter().is_sorted());
3369 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3370 /// assert!([0].iter().is_sorted());
3371 /// assert!(std::iter::empty::<i32>().is_sorted());
3372 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3375 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3376 fn is_sorted(self) -> bool
3379 Self::Item: PartialOrd,
3381 self.is_sorted_by(PartialOrd::partial_cmp)
3384 /// Checks if the elements of this iterator are sorted using the given comparator function.
3386 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3387 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3388 /// [`is_sorted`]; see its documentation for more information.
3393 /// #![feature(is_sorted)]
3395 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3396 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3397 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3398 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3399 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3402 /// [`is_sorted`]: Iterator::is_sorted
3403 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3404 fn is_sorted_by<F>(mut self, compare: F) -> bool
3407 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3412 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3413 ) -> impl FnMut(T) -> bool + 'a {
3415 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3423 let mut last = match self.next() {
3425 None => return true,
3428 self.all(check(&mut last, compare))
3431 /// Checks if the elements of this iterator are sorted using the given key extraction
3434 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3435 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3436 /// its documentation for more information.
3438 /// [`is_sorted`]: Iterator::is_sorted
3443 /// #![feature(is_sorted)]
3445 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3446 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3449 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3450 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3453 F: FnMut(Self::Item) -> K,
3456 self.map(f).is_sorted()
3459 /// See [TrustedRandomAccess]
3460 // The unusual name is to avoid name collisions in method resolution
3464 #[unstable(feature = "trusted_random_access", issue = "none")]
3465 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3467 Self: TrustedRandomAccessNoCoerce,
3469 unreachable!("Always specialized");
3473 #[stable(feature = "rust1", since = "1.0.0")]
3474 impl<I: Iterator + ?Sized> Iterator for &mut I {
3475 type Item = I::Item;
3476 fn next(&mut self) -> Option<I::Item> {
3479 fn size_hint(&self) -> (usize, Option<usize>) {
3480 (**self).size_hint()
3482 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3483 (**self).advance_by(n)
3485 fn nth(&mut self, n: usize) -> Option<Self::Item> {