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::Range<Idx>; 1]",
30 label = "if you meant to iterate between two values, remove the square brackets",
31 note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
32 without the brackets: `start..end`"
35 _Self = "[std::ops::RangeFrom<Idx>; 1]",
36 label = "if you meant to iterate from a value onwards, remove the square brackets",
37 note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
38 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
39 unbounded iterator will run forever unless you `break` or `return` from within the \
43 _Self = "[std::ops::RangeTo<Idx>; 1]",
44 label = "if you meant to iterate until a value, remove the square brackets and add a \
46 note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
47 `Range` without the brackets: `0..end`"
50 _Self = "[std::ops::RangeInclusive<Idx>; 1]",
51 label = "if you meant to iterate between two values, remove the square brackets",
52 note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
53 `RangeInclusive` without the brackets: `start..=end`"
56 _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
57 label = "if you meant to iterate until a value (including it), remove the square brackets \
58 and add a starting value",
59 note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
60 bounded `RangeInclusive` without the brackets: `0..=end`"
63 _Self = "std::ops::RangeTo<Idx>",
64 label = "if you meant to iterate until a value, add a starting value",
65 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
66 bounded `Range`: `0..end`"
69 _Self = "std::ops::RangeToInclusive<Idx>",
70 label = "if you meant to iterate until a value (including it), add a starting value",
71 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
72 to have a bounded `RangeInclusive`: `0..=end`"
76 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
79 _Self = "std::string::String",
80 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 label = "arrays do not yet implement `IntoIterator`; try using `std::array::IntoIter::new(arr)`",
85 note = "see <https://github.com/rust-lang/rust/pull/65819> for more details"
89 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
90 syntax `start..end` or the inclusive range syntax `start..=end`"
92 label = "`{Self}` is not an iterator",
93 message = "`{Self}` is not an iterator"
95 #[cfg_attr(bootstrap, doc(spotlight))]
96 #[cfg_attr(not(bootstrap), doc(notable_trait))]
97 #[rustc_diagnostic_item = "Iterator"]
98 #[must_use = "iterators are lazy and do nothing unless consumed"]
100 /// The type of the elements being iterated over.
101 #[stable(feature = "rust1", since = "1.0.0")]
104 /// Advances the iterator and returns the next value.
106 /// Returns [`None`] when iteration is finished. Individual iterator
107 /// implementations may choose to resume iteration, and so calling `next()`
108 /// again may or may not eventually start returning [`Some(Item)`] again at some
111 /// [`Some(Item)`]: Some
118 /// let a = [1, 2, 3];
120 /// let mut iter = a.iter();
122 /// // A call to next() returns the next value...
123 /// assert_eq!(Some(&1), iter.next());
124 /// assert_eq!(Some(&2), iter.next());
125 /// assert_eq!(Some(&3), iter.next());
127 /// // ... and then None once it's over.
128 /// assert_eq!(None, iter.next());
130 /// // More calls may or may not return `None`. Here, they always will.
131 /// assert_eq!(None, iter.next());
132 /// assert_eq!(None, iter.next());
135 #[stable(feature = "rust1", since = "1.0.0")]
136 fn next(&mut self) -> Option<Self::Item>;
138 /// Returns the bounds on the remaining length of the iterator.
140 /// Specifically, `size_hint()` returns a tuple where the first element
141 /// is the lower bound, and the second element is the upper bound.
143 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
144 /// A [`None`] here means that either there is no known upper bound, or the
145 /// upper bound is larger than [`usize`].
147 /// # Implementation notes
149 /// It is not enforced that an iterator implementation yields the declared
150 /// number of elements. A buggy iterator may yield less than the lower bound
151 /// or more than the upper bound of elements.
153 /// `size_hint()` is primarily intended to be used for optimizations such as
154 /// reserving space for the elements of the iterator, but must not be
155 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
156 /// implementation of `size_hint()` should not lead to memory safety
159 /// That said, the implementation should provide a correct estimation,
160 /// because otherwise it would be a violation of the trait's protocol.
162 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
165 /// [`usize`]: type@usize
172 /// let a = [1, 2, 3];
173 /// let iter = a.iter();
175 /// assert_eq!((3, Some(3)), iter.size_hint());
178 /// A more complex example:
181 /// // The even numbers from zero to ten.
182 /// let iter = (0..10).filter(|x| x % 2 == 0);
184 /// // We might iterate from zero to ten times. Knowing that it's five
185 /// // exactly wouldn't be possible without executing filter().
186 /// assert_eq!((0, Some(10)), iter.size_hint());
188 /// // Let's add five more numbers with chain()
189 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
191 /// // now both bounds are increased by five
192 /// assert_eq!((5, Some(15)), iter.size_hint());
195 /// Returning `None` for an upper bound:
198 /// // an infinite iterator has no upper bound
199 /// // and the maximum possible lower bound
202 /// assert_eq!((usize::MAX, None), iter.size_hint());
205 #[stable(feature = "rust1", since = "1.0.0")]
206 fn size_hint(&self) -> (usize, Option<usize>) {
210 /// Consumes the iterator, counting the number of iterations and returning it.
212 /// This method will call [`next`] repeatedly until [`None`] is encountered,
213 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
214 /// called at least once even if the iterator does not have any elements.
216 /// [`next`]: Iterator::next
218 /// # Overflow Behavior
220 /// The method does no guarding against overflows, so counting elements of
221 /// an iterator with more than [`usize::MAX`] elements either produces the
222 /// wrong result or panics. If debug assertions are enabled, a panic is
227 /// This function might panic if the iterator has more than [`usize::MAX`]
235 /// let a = [1, 2, 3];
236 /// assert_eq!(a.iter().count(), 3);
238 /// let a = [1, 2, 3, 4, 5];
239 /// assert_eq!(a.iter().count(), 5);
242 #[stable(feature = "rust1", since = "1.0.0")]
243 fn count(self) -> usize
249 #[rustc_inherit_overflow_checks]
250 |count, _| count + 1,
254 /// Consumes the iterator, returning the last element.
256 /// This method will evaluate the iterator until it returns [`None`]. While
257 /// doing so, it keeps track of the current element. After [`None`] is
258 /// returned, `last()` will then return the last element it saw.
265 /// let a = [1, 2, 3];
266 /// assert_eq!(a.iter().last(), Some(&3));
268 /// let a = [1, 2, 3, 4, 5];
269 /// assert_eq!(a.iter().last(), Some(&5));
272 #[stable(feature = "rust1", since = "1.0.0")]
273 fn last(self) -> Option<Self::Item>
278 fn some<T>(_: Option<T>, x: T) -> Option<T> {
282 self.fold(None, some)
285 /// Advances the iterator by `n` elements.
287 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
288 /// times until [`None`] is encountered.
290 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
291 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
292 /// of elements the iterator is advanced by before running out of elements (i.e. the
293 /// length of the iterator). Note that `k` is always less than `n`.
295 /// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
297 /// [`next`]: Iterator::next
304 /// #![feature(iter_advance_by)]
306 /// let a = [1, 2, 3, 4];
307 /// let mut iter = a.iter();
309 /// assert_eq!(iter.advance_by(2), Ok(()));
310 /// assert_eq!(iter.next(), Some(&3));
311 /// assert_eq!(iter.advance_by(0), Ok(()));
312 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
315 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
316 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
318 self.next().ok_or(i)?;
323 /// Returns the `n`th element of the iterator.
325 /// Like most indexing operations, the count starts from zero, so `nth(0)`
326 /// returns the first value, `nth(1)` the second, and so on.
328 /// Note that all preceding elements, as well as the returned element, will be
329 /// consumed from the iterator. That means that the preceding elements will be
330 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
331 /// will return different elements.
333 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
341 /// let a = [1, 2, 3];
342 /// assert_eq!(a.iter().nth(1), Some(&2));
345 /// Calling `nth()` multiple times doesn't rewind the iterator:
348 /// let a = [1, 2, 3];
350 /// let mut iter = a.iter();
352 /// assert_eq!(iter.nth(1), Some(&2));
353 /// assert_eq!(iter.nth(1), None);
356 /// Returning `None` if there are less than `n + 1` elements:
359 /// let a = [1, 2, 3];
360 /// assert_eq!(a.iter().nth(10), None);
363 #[stable(feature = "rust1", since = "1.0.0")]
364 fn nth(&mut self, n: usize) -> Option<Self::Item> {
365 self.advance_by(n).ok()?;
369 /// Creates an iterator starting at the same point, but stepping by
370 /// the given amount at each iteration.
372 /// Note 1: The first element of the iterator will always be returned,
373 /// regardless of the step given.
375 /// Note 2: The time at which ignored elements are pulled is not fixed.
376 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
377 /// but is also free to behave like the sequence
378 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
379 /// Which way is used may change for some iterators for performance reasons.
380 /// The second way will advance the iterator earlier and may consume more items.
382 /// `advance_n_and_return_first` is the equivalent of:
384 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
388 /// let next = iter.next();
389 /// if total_step > 1 {
390 /// iter.nth(total_step-2);
398 /// The method will panic if the given step is `0`.
405 /// let a = [0, 1, 2, 3, 4, 5];
406 /// let mut iter = a.iter().step_by(2);
408 /// assert_eq!(iter.next(), Some(&0));
409 /// assert_eq!(iter.next(), Some(&2));
410 /// assert_eq!(iter.next(), Some(&4));
411 /// assert_eq!(iter.next(), None);
414 #[stable(feature = "iterator_step_by", since = "1.28.0")]
415 fn step_by(self, step: usize) -> StepBy<Self>
419 StepBy::new(self, step)
422 /// Takes two iterators and creates a new iterator over both in sequence.
424 /// `chain()` will return a new iterator which will first iterate over
425 /// values from the first iterator and then over values from the second
428 /// In other words, it links two iterators together, in a chain. 🔗
430 /// [`once`] is commonly used to adapt a single value into a chain of
431 /// other kinds of iteration.
438 /// let a1 = [1, 2, 3];
439 /// let a2 = [4, 5, 6];
441 /// let mut iter = a1.iter().chain(a2.iter());
443 /// assert_eq!(iter.next(), Some(&1));
444 /// assert_eq!(iter.next(), Some(&2));
445 /// assert_eq!(iter.next(), Some(&3));
446 /// assert_eq!(iter.next(), Some(&4));
447 /// assert_eq!(iter.next(), Some(&5));
448 /// assert_eq!(iter.next(), Some(&6));
449 /// assert_eq!(iter.next(), None);
452 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
453 /// anything that can be converted into an [`Iterator`], not just an
454 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
455 /// [`IntoIterator`], and so can be passed to `chain()` directly:
458 /// let s1 = &[1, 2, 3];
459 /// let s2 = &[4, 5, 6];
461 /// let mut iter = s1.iter().chain(s2);
463 /// assert_eq!(iter.next(), Some(&1));
464 /// assert_eq!(iter.next(), Some(&2));
465 /// assert_eq!(iter.next(), Some(&3));
466 /// assert_eq!(iter.next(), Some(&4));
467 /// assert_eq!(iter.next(), Some(&5));
468 /// assert_eq!(iter.next(), Some(&6));
469 /// assert_eq!(iter.next(), None);
472 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
476 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
477 /// use std::os::windows::ffi::OsStrExt;
478 /// s.encode_wide().chain(std::iter::once(0)).collect()
482 /// [`once`]: crate::iter::once
483 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
485 #[stable(feature = "rust1", since = "1.0.0")]
486 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
489 U: IntoIterator<Item = Self::Item>,
491 Chain::new(self, other.into_iter())
494 /// 'Zips up' two iterators into a single iterator of pairs.
496 /// `zip()` returns a new iterator that will iterate over two other
497 /// iterators, returning a tuple where the first element comes from the
498 /// first iterator, and the second element comes from the second iterator.
500 /// In other words, it zips two iterators together, into a single one.
502 /// If either iterator returns [`None`], [`next`] from the zipped iterator
503 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
504 /// short-circuit and `next` will not be called on the second iterator.
511 /// let a1 = [1, 2, 3];
512 /// let a2 = [4, 5, 6];
514 /// let mut iter = a1.iter().zip(a2.iter());
516 /// assert_eq!(iter.next(), Some((&1, &4)));
517 /// assert_eq!(iter.next(), Some((&2, &5)));
518 /// assert_eq!(iter.next(), Some((&3, &6)));
519 /// assert_eq!(iter.next(), None);
522 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
523 /// anything that can be converted into an [`Iterator`], not just an
524 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
525 /// [`IntoIterator`], and so can be passed to `zip()` directly:
528 /// let s1 = &[1, 2, 3];
529 /// let s2 = &[4, 5, 6];
531 /// let mut iter = s1.iter().zip(s2);
533 /// assert_eq!(iter.next(), Some((&1, &4)));
534 /// assert_eq!(iter.next(), Some((&2, &5)));
535 /// assert_eq!(iter.next(), Some((&3, &6)));
536 /// assert_eq!(iter.next(), None);
539 /// `zip()` is often used to zip an infinite iterator to a finite one.
540 /// This works because the finite iterator will eventually return [`None`],
541 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
544 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
546 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
548 /// assert_eq!((0, 'f'), enumerate[0]);
549 /// assert_eq!((0, 'f'), zipper[0]);
551 /// assert_eq!((1, 'o'), enumerate[1]);
552 /// assert_eq!((1, 'o'), zipper[1]);
554 /// assert_eq!((2, 'o'), enumerate[2]);
555 /// assert_eq!((2, 'o'), zipper[2]);
558 /// [`enumerate`]: Iterator::enumerate
559 /// [`next`]: Iterator::next
561 #[stable(feature = "rust1", since = "1.0.0")]
562 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
567 Zip::new(self, other.into_iter())
570 /// Creates a new iterator which places a copy of `separator` between adjacent
571 /// items of the original iterator.
573 /// In case `separator` does not implement [`Clone`] or needs to be
574 /// computed every time, use [`intersperse_with`].
581 /// #![feature(iter_intersperse)]
583 /// let mut a = [0, 1, 2].iter().intersperse(&100);
584 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
585 /// assert_eq!(a.next(), Some(&100)); // The separator.
586 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
587 /// assert_eq!(a.next(), Some(&100)); // The separator.
588 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
589 /// assert_eq!(a.next(), None); // The iterator is finished.
592 /// `intersperse` can be very useful to join an iterator's items using a common element:
594 /// #![feature(iter_intersperse)]
596 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
597 /// assert_eq!(hello, "Hello World !");
600 /// [`Clone`]: crate::clone::Clone
601 /// [`intersperse_with`]: Iterator::intersperse_with
603 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
604 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
609 Intersperse::new(self, separator)
612 /// Creates a new iterator which places an item generated by `separator`
613 /// between adjacent items of the original iterator.
615 /// The closure will be called exactly once each time an item is placed
616 /// between two adjacent items from the underlying iterator; specifically,
617 /// the closure is not called if the underlying iterator yields less than
618 /// two items and after the last item is yielded.
620 /// If the iterator's item implements [`Clone`], it may be easier to use
628 /// #![feature(iter_intersperse)]
630 /// #[derive(PartialEq, Debug)]
631 /// struct NotClone(usize);
633 /// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
634 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
636 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
637 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
638 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
639 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
640 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
641 /// assert_eq!(it.next(), None); // The iterator is finished.
644 /// `intersperse_with` can be used in situations where the separator needs
647 /// #![feature(iter_intersperse)]
649 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
651 /// // The closure mutably borrows its context to generate an item.
652 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
653 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
655 /// let result = src.intersperse_with(separator).collect::<String>();
656 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
658 /// [`Clone`]: crate::clone::Clone
659 /// [`intersperse`]: Iterator::intersperse
661 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
662 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
665 G: FnMut() -> Self::Item,
667 IntersperseWith::new(self, separator)
670 /// Takes a closure and creates an iterator which calls that closure on each
673 /// `map()` transforms one iterator into another, by means of its argument:
674 /// something that implements [`FnMut`]. It produces a new iterator which
675 /// calls this closure on each element of the original iterator.
677 /// If you are good at thinking in types, you can think of `map()` like this:
678 /// If you have an iterator that gives you elements of some type `A`, and
679 /// you want an iterator of some other type `B`, you can use `map()`,
680 /// passing a closure that takes an `A` and returns a `B`.
682 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
683 /// lazy, it is best used when you're already working with other iterators.
684 /// If you're doing some sort of looping for a side effect, it's considered
685 /// more idiomatic to use [`for`] than `map()`.
687 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
688 /// [`FnMut`]: crate::ops::FnMut
695 /// let a = [1, 2, 3];
697 /// let mut iter = a.iter().map(|x| 2 * x);
699 /// assert_eq!(iter.next(), Some(2));
700 /// assert_eq!(iter.next(), Some(4));
701 /// assert_eq!(iter.next(), Some(6));
702 /// assert_eq!(iter.next(), None);
705 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
708 /// # #![allow(unused_must_use)]
709 /// // don't do this:
710 /// (0..5).map(|x| println!("{}", x));
712 /// // it won't even execute, as it is lazy. Rust will warn you about this.
714 /// // Instead, use for:
716 /// println!("{}", x);
720 #[stable(feature = "rust1", since = "1.0.0")]
721 fn map<B, F>(self, f: F) -> Map<Self, F>
724 F: FnMut(Self::Item) -> B,
729 /// Calls a closure on each element of an iterator.
731 /// This is equivalent to using a [`for`] loop on the iterator, although
732 /// `break` and `continue` are not possible from a closure. It's generally
733 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
734 /// when processing items at the end of longer iterator chains. In some
735 /// cases `for_each` may also be faster than a loop, because it will use
736 /// internal iteration on adaptors like `Chain`.
738 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
745 /// use std::sync::mpsc::channel;
747 /// let (tx, rx) = channel();
748 /// (0..5).map(|x| x * 2 + 1)
749 /// .for_each(move |x| tx.send(x).unwrap());
751 /// let v: Vec<_> = rx.iter().collect();
752 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
755 /// For such a small example, a `for` loop may be cleaner, but `for_each`
756 /// might be preferable to keep a functional style with longer iterators:
759 /// (0..5).flat_map(|x| x * 100 .. x * 110)
761 /// .filter(|&(i, x)| (i + x) % 3 == 0)
762 /// .for_each(|(i, x)| println!("{}:{}", i, x));
765 #[stable(feature = "iterator_for_each", since = "1.21.0")]
766 fn for_each<F>(self, f: F)
769 F: FnMut(Self::Item),
772 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
773 move |(), item| f(item)
776 self.fold((), call(f));
779 /// Creates an iterator which uses a closure to determine if an element
780 /// should be yielded.
782 /// Given an element the closure must return `true` or `false`. The returned
783 /// iterator will yield only the elements for which the closure returns
791 /// let a = [0i32, 1, 2];
793 /// let mut iter = a.iter().filter(|x| x.is_positive());
795 /// assert_eq!(iter.next(), Some(&1));
796 /// assert_eq!(iter.next(), Some(&2));
797 /// assert_eq!(iter.next(), None);
800 /// Because the closure passed to `filter()` takes a reference, and many
801 /// iterators iterate over references, this leads to a possibly confusing
802 /// situation, where the type of the closure is a double reference:
805 /// let a = [0, 1, 2];
807 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
809 /// assert_eq!(iter.next(), Some(&2));
810 /// assert_eq!(iter.next(), None);
813 /// It's common to instead use destructuring on the argument to strip away
817 /// let a = [0, 1, 2];
819 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
821 /// assert_eq!(iter.next(), Some(&2));
822 /// assert_eq!(iter.next(), None);
828 /// let a = [0, 1, 2];
830 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
832 /// assert_eq!(iter.next(), Some(&2));
833 /// assert_eq!(iter.next(), None);
838 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
840 #[stable(feature = "rust1", since = "1.0.0")]
841 fn filter<P>(self, predicate: P) -> Filter<Self, P>
844 P: FnMut(&Self::Item) -> bool,
846 Filter::new(self, predicate)
849 /// Creates an iterator that both filters and maps.
851 /// The returned iterator yields only the `value`s for which the supplied
852 /// closure returns `Some(value)`.
854 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
855 /// concise. The example below shows how a `map().filter().map()` can be
856 /// shortened to a single call to `filter_map`.
858 /// [`filter`]: Iterator::filter
859 /// [`map`]: Iterator::map
866 /// let a = ["1", "two", "NaN", "four", "5"];
868 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
870 /// assert_eq!(iter.next(), Some(1));
871 /// assert_eq!(iter.next(), Some(5));
872 /// assert_eq!(iter.next(), None);
875 /// Here's the same example, but with [`filter`] and [`map`]:
878 /// let a = ["1", "two", "NaN", "four", "5"];
879 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
880 /// assert_eq!(iter.next(), Some(1));
881 /// assert_eq!(iter.next(), Some(5));
882 /// assert_eq!(iter.next(), None);
885 #[stable(feature = "rust1", since = "1.0.0")]
886 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
889 F: FnMut(Self::Item) -> Option<B>,
891 FilterMap::new(self, f)
894 /// Creates an iterator which gives the current iteration count as well as
897 /// The iterator returned yields pairs `(i, val)`, where `i` is the
898 /// current index of iteration and `val` is the value returned by the
901 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
902 /// different sized integer, the [`zip`] function provides similar
905 /// # Overflow Behavior
907 /// The method does no guarding against overflows, so enumerating more than
908 /// [`usize::MAX`] elements either produces the wrong result or panics. If
909 /// debug assertions are enabled, a panic is guaranteed.
913 /// The returned iterator might panic if the to-be-returned index would
914 /// overflow a [`usize`].
916 /// [`usize`]: type@usize
917 /// [`zip`]: Iterator::zip
922 /// let a = ['a', 'b', 'c'];
924 /// let mut iter = a.iter().enumerate();
926 /// assert_eq!(iter.next(), Some((0, &'a')));
927 /// assert_eq!(iter.next(), Some((1, &'b')));
928 /// assert_eq!(iter.next(), Some((2, &'c')));
929 /// assert_eq!(iter.next(), None);
932 #[stable(feature = "rust1", since = "1.0.0")]
933 fn enumerate(self) -> Enumerate<Self>
940 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
941 /// to look at the next element of the iterator without consuming it. See
942 /// their documentation for more information.
944 /// Note that the underlying iterator is still advanced when [`peek`] or
945 /// [`peek_mut`] are called for the first time: In order to retrieve the
946 /// next element, [`next`] is called on the underlying iterator, hence any
947 /// side effects (i.e. anything other than fetching the next value) of
948 /// the [`next`] method will occur.
956 /// let xs = [1, 2, 3];
958 /// let mut iter = xs.iter().peekable();
960 /// // peek() lets us see into the future
961 /// assert_eq!(iter.peek(), Some(&&1));
962 /// assert_eq!(iter.next(), Some(&1));
964 /// assert_eq!(iter.next(), Some(&2));
966 /// // we can peek() multiple times, the iterator won't advance
967 /// assert_eq!(iter.peek(), Some(&&3));
968 /// assert_eq!(iter.peek(), Some(&&3));
970 /// assert_eq!(iter.next(), Some(&3));
972 /// // after the iterator is finished, so is peek()
973 /// assert_eq!(iter.peek(), None);
974 /// assert_eq!(iter.next(), None);
977 /// Using [`peek_mut`] to mutate the next item without advancing the
981 /// let xs = [1, 2, 3];
983 /// let mut iter = xs.iter().peekable();
985 /// // `peek_mut()` lets us see into the future
986 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
987 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
988 /// assert_eq!(iter.next(), Some(&1));
990 /// if let Some(mut p) = iter.peek_mut() {
991 /// assert_eq!(*p, &2);
992 /// // put a value into the iterator
996 /// // The value reappears as the iterator continues
997 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
999 /// [`peek`]: Peekable::peek
1000 /// [`peek_mut`]: Peekable::peek_mut
1001 /// [`next`]: Iterator::next
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 fn peekable(self) -> Peekable<Self>
1011 /// Creates an iterator that [`skip`]s elements based on a predicate.
1013 /// [`skip`]: Iterator::skip
1015 /// `skip_while()` takes a closure as an argument. It will call this
1016 /// closure on each element of the iterator, and ignore elements
1017 /// until it returns `false`.
1019 /// After `false` is returned, `skip_while()`'s job is over, and the
1020 /// rest of the elements are yielded.
1027 /// let a = [-1i32, 0, 1];
1029 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
1031 /// assert_eq!(iter.next(), Some(&0));
1032 /// assert_eq!(iter.next(), Some(&1));
1033 /// assert_eq!(iter.next(), None);
1036 /// Because the closure passed to `skip_while()` takes a reference, and many
1037 /// iterators iterate over references, this leads to a possibly confusing
1038 /// situation, where the type of the closure argument is a double reference:
1041 /// let a = [-1, 0, 1];
1043 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1045 /// assert_eq!(iter.next(), Some(&0));
1046 /// assert_eq!(iter.next(), Some(&1));
1047 /// assert_eq!(iter.next(), None);
1050 /// Stopping after an initial `false`:
1053 /// let a = [-1, 0, 1, -2];
1055 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1057 /// assert_eq!(iter.next(), Some(&0));
1058 /// assert_eq!(iter.next(), Some(&1));
1060 /// // while this would have been false, since we already got a false,
1061 /// // skip_while() isn't used any more
1062 /// assert_eq!(iter.next(), Some(&-2));
1064 /// assert_eq!(iter.next(), None);
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1071 P: FnMut(&Self::Item) -> bool,
1073 SkipWhile::new(self, predicate)
1076 /// Creates an iterator that yields elements based on a predicate.
1078 /// `take_while()` takes a closure as an argument. It will call this
1079 /// closure on each element of the iterator, and yield elements
1080 /// while it returns `true`.
1082 /// After `false` is returned, `take_while()`'s job is over, and the
1083 /// rest of the elements are ignored.
1090 /// let a = [-1i32, 0, 1];
1092 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1094 /// assert_eq!(iter.next(), Some(&-1));
1095 /// assert_eq!(iter.next(), None);
1098 /// Because the closure passed to `take_while()` takes a reference, and many
1099 /// iterators iterate over references, this leads to a possibly confusing
1100 /// situation, where the type of the closure is a double reference:
1103 /// let a = [-1, 0, 1];
1105 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1107 /// assert_eq!(iter.next(), Some(&-1));
1108 /// assert_eq!(iter.next(), None);
1111 /// Stopping after an initial `false`:
1114 /// let a = [-1, 0, 1, -2];
1116 /// let mut iter = a.iter().take_while(|x| **x < 0);
1118 /// assert_eq!(iter.next(), Some(&-1));
1120 /// // We have more elements that are less than zero, but since we already
1121 /// // got a false, take_while() isn't used any more
1122 /// assert_eq!(iter.next(), None);
1125 /// Because `take_while()` needs to look at the value in order to see if it
1126 /// should be included or not, consuming iterators will see that it is
1130 /// let a = [1, 2, 3, 4];
1131 /// let mut iter = a.iter();
1133 /// let result: Vec<i32> = iter.by_ref()
1134 /// .take_while(|n| **n != 3)
1138 /// assert_eq!(result, &[1, 2]);
1140 /// let result: Vec<i32> = iter.cloned().collect();
1142 /// assert_eq!(result, &[4]);
1145 /// The `3` is no longer there, because it was consumed in order to see if
1146 /// the iteration should stop, but wasn't placed back into the iterator.
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1152 P: FnMut(&Self::Item) -> bool,
1154 TakeWhile::new(self, predicate)
1157 /// Creates an iterator that both yields elements based on a predicate and maps.
1159 /// `map_while()` takes a closure as an argument. It will call this
1160 /// closure on each element of the iterator, and yield elements
1161 /// while it returns [`Some(_)`][`Some`].
1168 /// #![feature(iter_map_while)]
1169 /// let a = [-1i32, 4, 0, 1];
1171 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1173 /// assert_eq!(iter.next(), Some(-16));
1174 /// assert_eq!(iter.next(), Some(4));
1175 /// assert_eq!(iter.next(), None);
1178 /// Here's the same example, but with [`take_while`] and [`map`]:
1180 /// [`take_while`]: Iterator::take_while
1181 /// [`map`]: Iterator::map
1184 /// let a = [-1i32, 4, 0, 1];
1186 /// let mut iter = a.iter()
1187 /// .map(|x| 16i32.checked_div(*x))
1188 /// .take_while(|x| x.is_some())
1189 /// .map(|x| x.unwrap());
1191 /// assert_eq!(iter.next(), Some(-16));
1192 /// assert_eq!(iter.next(), Some(4));
1193 /// assert_eq!(iter.next(), None);
1196 /// Stopping after an initial [`None`]:
1199 /// #![feature(iter_map_while)]
1200 /// use std::convert::TryFrom;
1202 /// let a = [0, 1, 2, -3, 4, 5, -6];
1204 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1205 /// let vec = iter.collect::<Vec<_>>();
1207 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1208 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1209 /// assert_eq!(vec, vec![0, 1, 2]);
1212 /// Because `map_while()` needs to look at the value in order to see if it
1213 /// should be included or not, consuming iterators will see that it is
1217 /// #![feature(iter_map_while)]
1218 /// use std::convert::TryFrom;
1220 /// let a = [1, 2, -3, 4];
1221 /// let mut iter = a.iter();
1223 /// let result: Vec<u32> = iter.by_ref()
1224 /// .map_while(|n| u32::try_from(*n).ok())
1227 /// assert_eq!(result, &[1, 2]);
1229 /// let result: Vec<i32> = iter.cloned().collect();
1231 /// assert_eq!(result, &[4]);
1234 /// The `-3` is no longer there, because it was consumed in order to see if
1235 /// the iteration should stop, but wasn't placed back into the iterator.
1237 /// Note that unlike [`take_while`] this iterator is **not** fused.
1238 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1239 /// If you need fused iterator, use [`fuse`].
1241 /// [`fuse`]: Iterator::fuse
1243 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1244 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1247 P: FnMut(Self::Item) -> Option<B>,
1249 MapWhile::new(self, predicate)
1252 /// Creates an iterator that skips the first `n` elements.
1254 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1255 /// iterator is reached (whichever happens first). After that, all the remaining
1256 /// elements are yielded. In particular, if the original iterator is too short,
1257 /// then the returned iterator is empty.
1259 /// Rather than overriding this method directly, instead override the `nth` method.
1266 /// let a = [1, 2, 3];
1268 /// let mut iter = a.iter().skip(2);
1270 /// assert_eq!(iter.next(), Some(&3));
1271 /// assert_eq!(iter.next(), None);
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 fn skip(self, n: usize) -> Skip<Self>
1282 /// Creates an iterator that yields the first `n` elements, or fewer
1283 /// if the underlying iterator ends sooner.
1285 /// `take(n)` yields elements until `n` elements are yielded or the end of
1286 /// the iterator is reached (whichever happens first).
1287 /// The returned iterator is a prefix of length `n` if the original iterator
1288 /// contains at least `n` elements, otherwise it contains all of the
1289 /// (fewer than `n`) elements of the original iterator.
1296 /// let a = [1, 2, 3];
1298 /// let mut iter = a.iter().take(2);
1300 /// assert_eq!(iter.next(), Some(&1));
1301 /// assert_eq!(iter.next(), Some(&2));
1302 /// assert_eq!(iter.next(), None);
1305 /// `take()` is often used with an infinite iterator, to make it finite:
1308 /// let mut iter = (0..).take(3);
1310 /// assert_eq!(iter.next(), Some(0));
1311 /// assert_eq!(iter.next(), Some(1));
1312 /// assert_eq!(iter.next(), Some(2));
1313 /// assert_eq!(iter.next(), None);
1316 /// If less than `n` elements are available,
1317 /// `take` will limit itself to the size of the underlying iterator:
1320 /// let v = vec![1, 2];
1321 /// let mut iter = v.into_iter().take(5);
1322 /// assert_eq!(iter.next(), Some(1));
1323 /// assert_eq!(iter.next(), Some(2));
1324 /// assert_eq!(iter.next(), None);
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 fn take(self, n: usize) -> Take<Self>
1335 /// An iterator adaptor similar to [`fold`] that holds internal state and
1336 /// produces a new iterator.
1338 /// [`fold`]: Iterator::fold
1340 /// `scan()` takes two arguments: an initial value which seeds the internal
1341 /// state, and a closure with two arguments, the first being a mutable
1342 /// reference to the internal state and the second an iterator element.
1343 /// The closure can assign to the internal state to share state between
1346 /// On iteration, the closure will be applied to each element of the
1347 /// iterator and the return value from the closure, an [`Option`], is
1348 /// yielded by the iterator.
1355 /// let a = [1, 2, 3];
1357 /// let mut iter = a.iter().scan(1, |state, &x| {
1358 /// // each iteration, we'll multiply the state by the element
1359 /// *state = *state * x;
1361 /// // then, we'll yield the negation of the state
1365 /// assert_eq!(iter.next(), Some(-1));
1366 /// assert_eq!(iter.next(), Some(-2));
1367 /// assert_eq!(iter.next(), Some(-6));
1368 /// assert_eq!(iter.next(), None);
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1375 F: FnMut(&mut St, Self::Item) -> Option<B>,
1377 Scan::new(self, initial_state, f)
1380 /// Creates an iterator that works like map, but flattens nested structure.
1382 /// The [`map`] adapter is very useful, but only when the closure
1383 /// argument produces values. If it produces an iterator instead, there's
1384 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1387 /// You can think of `flat_map(f)` as the semantic equivalent
1388 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1390 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1391 /// one item for each element, and `flat_map()`'s closure returns an
1392 /// iterator for each element.
1394 /// [`map`]: Iterator::map
1395 /// [`flatten`]: Iterator::flatten
1402 /// let words = ["alpha", "beta", "gamma"];
1404 /// // chars() returns an iterator
1405 /// let merged: String = words.iter()
1406 /// .flat_map(|s| s.chars())
1408 /// assert_eq!(merged, "alphabetagamma");
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1416 F: FnMut(Self::Item) -> U,
1418 FlatMap::new(self, f)
1421 /// Creates an iterator that flattens nested structure.
1423 /// This is useful when you have an iterator of iterators or an iterator of
1424 /// things that can be turned into iterators and you want to remove one
1425 /// level of indirection.
1432 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1433 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1434 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1437 /// Mapping and then flattening:
1440 /// let words = ["alpha", "beta", "gamma"];
1442 /// // chars() returns an iterator
1443 /// let merged: String = words.iter()
1444 /// .map(|s| s.chars())
1447 /// assert_eq!(merged, "alphabetagamma");
1450 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1451 /// in this case since it conveys intent more clearly:
1454 /// let words = ["alpha", "beta", "gamma"];
1456 /// // chars() returns an iterator
1457 /// let merged: String = words.iter()
1458 /// .flat_map(|s| s.chars())
1460 /// assert_eq!(merged, "alphabetagamma");
1463 /// Flattening only removes one level of nesting at a time:
1466 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1468 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1469 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1471 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1472 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1475 /// Here we see that `flatten()` does not perform a "deep" flatten.
1476 /// Instead, only one level of nesting is removed. That is, if you
1477 /// `flatten()` a three-dimensional array, the result will be
1478 /// two-dimensional and not one-dimensional. To get a one-dimensional
1479 /// structure, you have to `flatten()` again.
1481 /// [`flat_map()`]: Iterator::flat_map
1483 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1484 fn flatten(self) -> Flatten<Self>
1487 Self::Item: IntoIterator,
1492 /// Creates an iterator which ends after the first [`None`].
1494 /// After an iterator returns [`None`], future calls may or may not yield
1495 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1496 /// [`None`] is given, it will always return [`None`] forever.
1498 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1499 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1500 /// if the [`FusedIterator`] trait is improperly implemented.
1502 /// [`Some(T)`]: Some
1503 /// [`FusedIterator`]: crate::iter::FusedIterator
1510 /// // an iterator which alternates between Some and None
1511 /// struct Alternate {
1515 /// impl Iterator for Alternate {
1516 /// type Item = i32;
1518 /// fn next(&mut self) -> Option<i32> {
1519 /// let val = self.state;
1520 /// self.state = self.state + 1;
1522 /// // if it's even, Some(i32), else None
1523 /// if val % 2 == 0 {
1531 /// let mut iter = Alternate { state: 0 };
1533 /// // we can see our iterator going back and forth
1534 /// assert_eq!(iter.next(), Some(0));
1535 /// assert_eq!(iter.next(), None);
1536 /// assert_eq!(iter.next(), Some(2));
1537 /// assert_eq!(iter.next(), None);
1539 /// // however, once we fuse it...
1540 /// let mut iter = iter.fuse();
1542 /// assert_eq!(iter.next(), Some(4));
1543 /// assert_eq!(iter.next(), None);
1545 /// // it will always return `None` after the first time.
1546 /// assert_eq!(iter.next(), None);
1547 /// assert_eq!(iter.next(), None);
1548 /// assert_eq!(iter.next(), None);
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 fn fuse(self) -> Fuse<Self>
1559 /// Does something with each element of an iterator, passing the value on.
1561 /// When using iterators, you'll often chain several of them together.
1562 /// While working on such code, you might want to check out what's
1563 /// happening at various parts in the pipeline. To do that, insert
1564 /// a call to `inspect()`.
1566 /// It's more common for `inspect()` to be used as a debugging tool than to
1567 /// exist in your final code, but applications may find it useful in certain
1568 /// situations when errors need to be logged before being discarded.
1575 /// let a = [1, 4, 2, 3];
1577 /// // this iterator sequence is complex.
1578 /// let sum = a.iter()
1580 /// .filter(|x| x % 2 == 0)
1581 /// .fold(0, |sum, i| sum + i);
1583 /// println!("{}", sum);
1585 /// // let's add some inspect() calls to investigate what's happening
1586 /// let sum = a.iter()
1588 /// .inspect(|x| println!("about to filter: {}", x))
1589 /// .filter(|x| x % 2 == 0)
1590 /// .inspect(|x| println!("made it through filter: {}", x))
1591 /// .fold(0, |sum, i| sum + i);
1593 /// println!("{}", sum);
1596 /// This will print:
1600 /// about to filter: 1
1601 /// about to filter: 4
1602 /// made it through filter: 4
1603 /// about to filter: 2
1604 /// made it through filter: 2
1605 /// about to filter: 3
1609 /// Logging errors before discarding them:
1612 /// let lines = ["1", "2", "a"];
1614 /// let sum: i32 = lines
1616 /// .map(|line| line.parse::<i32>())
1617 /// .inspect(|num| {
1618 /// if let Err(ref e) = *num {
1619 /// println!("Parsing error: {}", e);
1622 /// .filter_map(Result::ok)
1625 /// println!("Sum: {}", sum);
1628 /// This will print:
1631 /// Parsing error: invalid digit found in string
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1639 F: FnMut(&Self::Item),
1641 Inspect::new(self, f)
1644 /// Borrows an iterator, rather than consuming it.
1646 /// This is useful to allow applying iterator adaptors while still
1647 /// retaining ownership of the original iterator.
1654 /// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
1656 /// // Take the first two words.
1657 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1658 /// assert_eq!(hello_world, vec!["hello", "world"]);
1660 /// // Collect the rest of the words.
1661 /// // We can only do this because we used `by_ref` earlier.
1662 /// let of_rust: Vec<_> = words.collect();
1663 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 fn by_ref(&mut self) -> &mut Self
1673 /// Transforms an iterator into a collection.
1675 /// `collect()` can take anything iterable, and turn it into a relevant
1676 /// collection. This is one of the more powerful methods in the standard
1677 /// library, used in a variety of contexts.
1679 /// The most basic pattern in which `collect()` is used is to turn one
1680 /// collection into another. You take a collection, call [`iter`] on it,
1681 /// do a bunch of transformations, and then `collect()` at the end.
1683 /// `collect()` can also create instances of types that are not typical
1684 /// collections. For example, a [`String`] can be built from [`char`]s,
1685 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1686 /// into `Result<Collection<T>, E>`. See the examples below for more.
1688 /// Because `collect()` is so general, it can cause problems with type
1689 /// inference. As such, `collect()` is one of the few times you'll see
1690 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1691 /// helps the inference algorithm understand specifically which collection
1692 /// you're trying to collect into.
1699 /// let a = [1, 2, 3];
1701 /// let doubled: Vec<i32> = a.iter()
1702 /// .map(|&x| x * 2)
1705 /// assert_eq!(vec![2, 4, 6], doubled);
1708 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1709 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1711 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1714 /// use std::collections::VecDeque;
1716 /// let a = [1, 2, 3];
1718 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1720 /// assert_eq!(2, doubled[0]);
1721 /// assert_eq!(4, doubled[1]);
1722 /// assert_eq!(6, doubled[2]);
1725 /// Using the 'turbofish' instead of annotating `doubled`:
1728 /// let a = [1, 2, 3];
1730 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1732 /// assert_eq!(vec![2, 4, 6], doubled);
1735 /// Because `collect()` only cares about what you're collecting into, you can
1736 /// still use a partial type hint, `_`, with the turbofish:
1739 /// let a = [1, 2, 3];
1741 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1743 /// assert_eq!(vec![2, 4, 6], doubled);
1746 /// Using `collect()` to make a [`String`]:
1749 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1751 /// let hello: String = chars.iter()
1752 /// .map(|&x| x as u8)
1753 /// .map(|x| (x + 1) as char)
1756 /// assert_eq!("hello", hello);
1759 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1760 /// see if any of them failed:
1763 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1765 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1767 /// // gives us the first error
1768 /// assert_eq!(Err("nope"), result);
1770 /// let results = [Ok(1), Ok(3)];
1772 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1774 /// // gives us the list of answers
1775 /// assert_eq!(Ok(vec![1, 3]), result);
1778 /// [`iter`]: Iterator::next
1779 /// [`String`]: ../../std/string/struct.String.html
1780 /// [`char`]: type@char
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1784 fn collect<B: FromIterator<Self::Item>>(self) -> B
1788 FromIterator::from_iter(self)
1791 /// Consumes an iterator, creating two collections from it.
1793 /// The predicate passed to `partition()` can return `true`, or `false`.
1794 /// `partition()` returns a pair, all of the elements for which it returned
1795 /// `true`, and all of the elements for which it returned `false`.
1797 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1799 /// [`is_partitioned()`]: Iterator::is_partitioned
1800 /// [`partition_in_place()`]: Iterator::partition_in_place
1807 /// let a = [1, 2, 3];
1809 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1811 /// .partition(|&n| n % 2 == 0);
1813 /// assert_eq!(even, vec![2]);
1814 /// assert_eq!(odd, vec![1, 3]);
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 fn partition<B, F>(self, f: F) -> (B, B)
1820 B: Default + Extend<Self::Item>,
1821 F: FnMut(&Self::Item) -> bool,
1824 fn extend<'a, T, B: Extend<T>>(
1825 mut f: impl FnMut(&T) -> bool + 'a,
1828 ) -> impl FnMut((), T) + 'a {
1833 right.extend_one(x);
1838 let mut left: B = Default::default();
1839 let mut right: B = Default::default();
1841 self.fold((), extend(f, &mut left, &mut right));
1846 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1847 /// such that all those that return `true` precede all those that return `false`.
1848 /// Returns the number of `true` elements found.
1850 /// The relative order of partitioned items is not maintained.
1852 /// See also [`is_partitioned()`] and [`partition()`].
1854 /// [`is_partitioned()`]: Iterator::is_partitioned
1855 /// [`partition()`]: Iterator::partition
1860 /// #![feature(iter_partition_in_place)]
1862 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1864 /// // Partition in-place between evens and odds
1865 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1867 /// assert_eq!(i, 3);
1868 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1869 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1871 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1872 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1874 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1875 P: FnMut(&T) -> bool,
1877 // FIXME: should we worry about the count overflowing? The only way to have more than
1878 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1880 // These closure "factory" functions exist to avoid genericity in `Self`.
1884 predicate: &'a mut impl FnMut(&T) -> bool,
1885 true_count: &'a mut usize,
1886 ) -> impl FnMut(&&mut T) -> bool + 'a {
1888 let p = predicate(&**x);
1889 *true_count += p as usize;
1895 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1896 move |x| predicate(&**x)
1899 // Repeatedly find the first `false` and swap it with the last `true`.
1900 let mut true_count = 0;
1901 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1902 if let Some(tail) = self.rfind(is_true(predicate)) {
1903 crate::mem::swap(head, tail);
1912 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1913 /// such that all those that return `true` precede all those that return `false`.
1915 /// See also [`partition()`] and [`partition_in_place()`].
1917 /// [`partition()`]: Iterator::partition
1918 /// [`partition_in_place()`]: Iterator::partition_in_place
1923 /// #![feature(iter_is_partitioned)]
1925 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1926 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1928 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1929 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1932 P: FnMut(Self::Item) -> bool,
1934 // Either all items test `true`, or the first clause stops at `false`
1935 // and we check that there are no more `true` items after that.
1936 self.all(&mut predicate) || !self.any(predicate)
1939 /// An iterator method that applies a function as long as it returns
1940 /// successfully, producing a single, final value.
1942 /// `try_fold()` takes two arguments: an initial value, and a closure with
1943 /// two arguments: an 'accumulator', and an element. The closure either
1944 /// returns successfully, with the value that the accumulator should have
1945 /// for the next iteration, or it returns failure, with an error value that
1946 /// is propagated back to the caller immediately (short-circuiting).
1948 /// The initial value is the value the accumulator will have on the first
1949 /// call. If applying the closure succeeded against every element of the
1950 /// iterator, `try_fold()` returns the final accumulator as success.
1952 /// Folding is useful whenever you have a collection of something, and want
1953 /// to produce a single value from it.
1955 /// # Note to Implementors
1957 /// Several of the other (forward) methods have default implementations in
1958 /// terms of this one, so try to implement this explicitly if it can
1959 /// do something better than the default `for` loop implementation.
1961 /// In particular, try to have this call `try_fold()` on the internal parts
1962 /// from which this iterator is composed. If multiple calls are needed,
1963 /// the `?` operator may be convenient for chaining the accumulator value
1964 /// along, but beware any invariants that need to be upheld before those
1965 /// early returns. This is a `&mut self` method, so iteration needs to be
1966 /// resumable after hitting an error here.
1973 /// let a = [1, 2, 3];
1975 /// // the checked sum of all of the elements of the array
1976 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1978 /// assert_eq!(sum, Some(6));
1981 /// Short-circuiting:
1984 /// let a = [10, 20, 30, 100, 40, 50];
1985 /// let mut it = a.iter();
1987 /// // This sum overflows when adding the 100 element
1988 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1989 /// assert_eq!(sum, None);
1991 /// // Because it short-circuited, the remaining elements are still
1992 /// // available through the iterator.
1993 /// assert_eq!(it.len(), 2);
1994 /// assert_eq!(it.next(), Some(&40));
1997 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1998 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2001 F: FnMut(B, Self::Item) -> R,
2004 let mut accum = init;
2005 while let Some(x) = self.next() {
2006 accum = f(accum, x)?;
2011 /// An iterator method that applies a fallible function to each item in the
2012 /// iterator, stopping at the first error and returning that error.
2014 /// This can also be thought of as the fallible form of [`for_each()`]
2015 /// or as the stateless version of [`try_fold()`].
2017 /// [`for_each()`]: Iterator::for_each
2018 /// [`try_fold()`]: Iterator::try_fold
2023 /// use std::fs::rename;
2024 /// use std::io::{stdout, Write};
2025 /// use std::path::Path;
2027 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2029 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
2030 /// assert!(res.is_ok());
2032 /// let mut it = data.iter().cloned();
2033 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2034 /// assert!(res.is_err());
2035 /// // It short-circuited, so the remaining items are still in the iterator:
2036 /// assert_eq!(it.next(), Some("stale_bread.json"));
2039 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2040 fn try_for_each<F, R>(&mut self, f: F) -> R
2043 F: FnMut(Self::Item) -> R,
2047 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2051 self.try_fold((), call(f))
2054 /// Folds every element into an accumulator by applying an operation,
2055 /// returning the final result.
2057 /// `fold()` takes two arguments: an initial value, and a closure with two
2058 /// arguments: an 'accumulator', and an element. The closure returns the value that
2059 /// the accumulator should have for the next iteration.
2061 /// The initial value is the value the accumulator will have on the first
2064 /// After applying this closure to every element of the iterator, `fold()`
2065 /// returns the accumulator.
2067 /// This operation is sometimes called 'reduce' or 'inject'.
2069 /// Folding is useful whenever you have a collection of something, and want
2070 /// to produce a single value from it.
2072 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2073 /// may not terminate for infinite iterators, even on traits for which a
2074 /// result is determinable in finite time.
2076 /// Note: [`reduce()`] can be used to use the first element as the initial
2077 /// value, if the accumulator type and item type is the same.
2079 /// # Note to Implementors
2081 /// Several of the other (forward) methods have default implementations in
2082 /// terms of this one, so try to implement this explicitly if it can
2083 /// do something better than the default `for` loop implementation.
2085 /// In particular, try to have this call `fold()` on the internal parts
2086 /// from which this iterator is composed.
2093 /// let a = [1, 2, 3];
2095 /// // the sum of all of the elements of the array
2096 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2098 /// assert_eq!(sum, 6);
2101 /// Let's walk through each step of the iteration here:
2103 /// | element | acc | x | result |
2104 /// |---------|-----|---|--------|
2106 /// | 1 | 0 | 1 | 1 |
2107 /// | 2 | 1 | 2 | 3 |
2108 /// | 3 | 3 | 3 | 6 |
2110 /// And so, our final result, `6`.
2112 /// It's common for people who haven't used iterators a lot to
2113 /// use a `for` loop with a list of things to build up a result. Those
2114 /// can be turned into `fold()`s:
2116 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2119 /// let numbers = [1, 2, 3, 4, 5];
2121 /// let mut result = 0;
2124 /// for i in &numbers {
2125 /// result = result + i;
2129 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2131 /// // they're the same
2132 /// assert_eq!(result, result2);
2135 /// [`reduce()`]: Iterator::reduce
2136 #[doc(alias = "reduce")]
2137 #[doc(alias = "inject")]
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2143 F: FnMut(B, Self::Item) -> B,
2145 let mut accum = init;
2146 while let Some(x) = self.next() {
2147 accum = f(accum, x);
2152 /// Reduces the elements to a single one, by repeatedly applying a reducing
2155 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2156 /// result of the reduction.
2158 /// For iterators with at least one element, this is the same as [`fold()`]
2159 /// with the first element of the iterator as the initial value, folding
2160 /// every subsequent element into it.
2162 /// [`fold()`]: Iterator::fold
2166 /// Find the maximum value:
2169 /// fn find_max<I>(iter: I) -> Option<I::Item>
2170 /// where I: Iterator,
2173 /// iter.reduce(|a, b| {
2174 /// if a >= b { a } else { b }
2177 /// let a = [10, 20, 5, -23, 0];
2178 /// let b: [u32; 0] = [];
2180 /// assert_eq!(find_max(a.iter()), Some(&20));
2181 /// assert_eq!(find_max(b.iter()), None);
2184 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2185 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2188 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2190 let first = self.next()?;
2191 Some(self.fold(first, f))
2194 /// Tests if every element of the iterator matches a predicate.
2196 /// `all()` takes a closure that returns `true` or `false`. It applies
2197 /// this closure to each element of the iterator, and if they all return
2198 /// `true`, then so does `all()`. If any of them return `false`, it
2199 /// returns `false`.
2201 /// `all()` is short-circuiting; in other words, it will stop processing
2202 /// as soon as it finds a `false`, given that no matter what else happens,
2203 /// the result will also be `false`.
2205 /// An empty iterator returns `true`.
2212 /// let a = [1, 2, 3];
2214 /// assert!(a.iter().all(|&x| x > 0));
2216 /// assert!(!a.iter().all(|&x| x > 2));
2219 /// Stopping at the first `false`:
2222 /// let a = [1, 2, 3];
2224 /// let mut iter = a.iter();
2226 /// assert!(!iter.all(|&x| x != 2));
2228 /// // we can still use `iter`, as there are more elements.
2229 /// assert_eq!(iter.next(), Some(&3));
2231 #[doc(alias = "every")]
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 fn all<F>(&mut self, f: F) -> bool
2237 F: FnMut(Self::Item) -> bool,
2240 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2242 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2245 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2248 /// Tests if any element of the iterator matches a predicate.
2250 /// `any()` takes a closure that returns `true` or `false`. It applies
2251 /// this closure to each element of the iterator, and if any of them return
2252 /// `true`, then so does `any()`. If they all return `false`, it
2253 /// returns `false`.
2255 /// `any()` is short-circuiting; in other words, it will stop processing
2256 /// as soon as it finds a `true`, given that no matter what else happens,
2257 /// the result will also be `true`.
2259 /// An empty iterator returns `false`.
2266 /// let a = [1, 2, 3];
2268 /// assert!(a.iter().any(|&x| x > 0));
2270 /// assert!(!a.iter().any(|&x| x > 5));
2273 /// Stopping at the first `true`:
2276 /// let a = [1, 2, 3];
2278 /// let mut iter = a.iter();
2280 /// assert!(iter.any(|&x| x != 2));
2282 /// // we can still use `iter`, as there are more elements.
2283 /// assert_eq!(iter.next(), Some(&2));
2286 #[stable(feature = "rust1", since = "1.0.0")]
2287 fn any<F>(&mut self, f: F) -> bool
2290 F: FnMut(Self::Item) -> bool,
2293 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2295 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2299 self.try_fold((), check(f)) == ControlFlow::BREAK
2302 /// Searches for an element of an iterator that satisfies a predicate.
2304 /// `find()` takes a closure that returns `true` or `false`. It applies
2305 /// this closure to each element of the iterator, and if any of them return
2306 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2307 /// `false`, it returns [`None`].
2309 /// `find()` is short-circuiting; in other words, it will stop processing
2310 /// as soon as the closure returns `true`.
2312 /// Because `find()` takes a reference, and many iterators iterate over
2313 /// references, this leads to a possibly confusing situation where the
2314 /// argument is a double reference. You can see this effect in the
2315 /// examples below, with `&&x`.
2317 /// [`Some(element)`]: Some
2324 /// let a = [1, 2, 3];
2326 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2328 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2331 /// Stopping at the first `true`:
2334 /// let a = [1, 2, 3];
2336 /// let mut iter = a.iter();
2338 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2340 /// // we can still use `iter`, as there are more elements.
2341 /// assert_eq!(iter.next(), Some(&3));
2344 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2346 #[stable(feature = "rust1", since = "1.0.0")]
2347 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2350 P: FnMut(&Self::Item) -> bool,
2353 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2355 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2359 self.try_fold((), check(predicate)).break_value()
2362 /// Applies function to the elements of iterator and returns
2363 /// the first non-none result.
2365 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2370 /// let a = ["lol", "NaN", "2", "5"];
2372 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2374 /// assert_eq!(first_number, Some(2));
2377 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2378 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2381 F: FnMut(Self::Item) -> Option<B>,
2384 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2385 move |(), x| match f(x) {
2386 Some(x) => ControlFlow::Break(x),
2387 None => ControlFlow::CONTINUE,
2391 self.try_fold((), check(f)).break_value()
2394 /// Applies function to the elements of iterator and returns
2395 /// the first true result or the first error.
2400 /// #![feature(try_find)]
2402 /// let a = ["1", "2", "lol", "NaN", "5"];
2404 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2405 /// Ok(s.parse::<i32>()? == search)
2408 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2409 /// assert_eq!(result, Ok(Some(&"2")));
2411 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2412 /// assert!(result.is_err());
2415 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2416 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2419 F: FnMut(&Self::Item) -> R,
2423 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, R::Error>>
2428 move |(), x| match f(&x).into_result() {
2429 Ok(false) => ControlFlow::CONTINUE,
2430 Ok(true) => ControlFlow::Break(Ok(x)),
2431 Err(x) => ControlFlow::Break(Err(x)),
2435 self.try_fold((), check(f)).break_value().transpose()
2438 /// Searches for an element in an iterator, returning its index.
2440 /// `position()` takes a closure that returns `true` or `false`. It applies
2441 /// this closure to each element of the iterator, and if one of them
2442 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2443 /// them return `false`, it returns [`None`].
2445 /// `position()` is short-circuiting; in other words, it will stop
2446 /// processing as soon as it finds a `true`.
2448 /// # Overflow Behavior
2450 /// The method does no guarding against overflows, so if there are more
2451 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2452 /// result or panics. If debug assertions are enabled, a panic is
2457 /// This function might panic if the iterator has more than `usize::MAX`
2458 /// non-matching elements.
2460 /// [`Some(index)`]: Some
2467 /// let a = [1, 2, 3];
2469 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2471 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2474 /// Stopping at the first `true`:
2477 /// let a = [1, 2, 3, 4];
2479 /// let mut iter = a.iter();
2481 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2483 /// // we can still use `iter`, as there are more elements.
2484 /// assert_eq!(iter.next(), Some(&3));
2486 /// // The returned index depends on iterator state
2487 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2491 #[stable(feature = "rust1", since = "1.0.0")]
2492 fn position<P>(&mut self, predicate: P) -> Option<usize>
2495 P: FnMut(Self::Item) -> bool,
2499 mut predicate: impl FnMut(T) -> bool,
2500 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2501 #[rustc_inherit_overflow_checks]
2503 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2507 self.try_fold(0, check(predicate)).break_value()
2510 /// Searches for an element in an iterator from the right, returning its
2513 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2514 /// this closure to each element of the iterator, starting from the end,
2515 /// and if one of them returns `true`, then `rposition()` returns
2516 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2518 /// `rposition()` is short-circuiting; in other words, it will stop
2519 /// processing as soon as it finds a `true`.
2521 /// [`Some(index)`]: Some
2528 /// let a = [1, 2, 3];
2530 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2532 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2535 /// Stopping at the first `true`:
2538 /// let a = [1, 2, 3];
2540 /// let mut iter = a.iter();
2542 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2544 /// // we can still use `iter`, as there are more elements.
2545 /// assert_eq!(iter.next(), Some(&1));
2548 #[stable(feature = "rust1", since = "1.0.0")]
2549 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2551 P: FnMut(Self::Item) -> bool,
2552 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2554 // No need for an overflow check here, because `ExactSizeIterator`
2555 // implies that the number of elements fits into a `usize`.
2558 mut predicate: impl FnMut(T) -> bool,
2559 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2562 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2567 self.try_rfold(n, check(predicate)).break_value()
2570 /// Returns the maximum element of an iterator.
2572 /// If several elements are equally maximum, the last element is
2573 /// returned. If the iterator is empty, [`None`] is returned.
2580 /// let a = [1, 2, 3];
2581 /// let b: Vec<u32> = Vec::new();
2583 /// assert_eq!(a.iter().max(), Some(&3));
2584 /// assert_eq!(b.iter().max(), None);
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 fn max(self) -> Option<Self::Item>
2593 self.max_by(Ord::cmp)
2596 /// Returns the minimum element of an iterator.
2598 /// If several elements are equally minimum, the first element is
2599 /// returned. If the iterator is empty, [`None`] is returned.
2606 /// let a = [1, 2, 3];
2607 /// let b: Vec<u32> = Vec::new();
2609 /// assert_eq!(a.iter().min(), Some(&1));
2610 /// assert_eq!(b.iter().min(), None);
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 fn min(self) -> Option<Self::Item>
2619 self.min_by(Ord::cmp)
2622 /// Returns the element that gives the maximum value from the
2623 /// specified function.
2625 /// If several elements are equally maximum, the last element is
2626 /// returned. If the iterator is empty, [`None`] is returned.
2631 /// let a = [-3_i32, 0, 1, 5, -10];
2632 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2635 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2636 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2639 F: FnMut(&Self::Item) -> B,
2642 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2647 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2651 let (_, x) = self.map(key(f)).max_by(compare)?;
2655 /// Returns the element that gives the maximum value with respect to the
2656 /// specified comparison function.
2658 /// If several elements are equally maximum, the last element is
2659 /// returned. If the iterator is empty, [`None`] is returned.
2664 /// let a = [-3_i32, 0, 1, 5, -10];
2665 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2668 #[stable(feature = "iter_max_by", since = "1.15.0")]
2669 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2672 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2675 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2676 move |x, y| cmp::max_by(x, y, &mut compare)
2679 self.reduce(fold(compare))
2682 /// Returns the element that gives the minimum value from the
2683 /// specified function.
2685 /// If several elements are equally minimum, the first element is
2686 /// returned. If the iterator is empty, [`None`] is returned.
2691 /// let a = [-3_i32, 0, 1, 5, -10];
2692 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2695 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2696 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2699 F: FnMut(&Self::Item) -> B,
2702 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2707 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2711 let (_, x) = self.map(key(f)).min_by(compare)?;
2715 /// Returns the element that gives the minimum value with respect to the
2716 /// specified comparison function.
2718 /// If several elements are equally minimum, the first element is
2719 /// returned. If the iterator is empty, [`None`] is returned.
2724 /// let a = [-3_i32, 0, 1, 5, -10];
2725 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2728 #[stable(feature = "iter_min_by", since = "1.15.0")]
2729 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2732 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2735 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2736 move |x, y| cmp::min_by(x, y, &mut compare)
2739 self.reduce(fold(compare))
2742 /// Reverses an iterator's direction.
2744 /// Usually, iterators iterate from left to right. After using `rev()`,
2745 /// an iterator will instead iterate from right to left.
2747 /// This is only possible if the iterator has an end, so `rev()` only
2748 /// works on [`DoubleEndedIterator`]s.
2753 /// let a = [1, 2, 3];
2755 /// let mut iter = a.iter().rev();
2757 /// assert_eq!(iter.next(), Some(&3));
2758 /// assert_eq!(iter.next(), Some(&2));
2759 /// assert_eq!(iter.next(), Some(&1));
2761 /// assert_eq!(iter.next(), None);
2764 #[doc(alias = "reverse")]
2765 #[stable(feature = "rust1", since = "1.0.0")]
2766 fn rev(self) -> Rev<Self>
2768 Self: Sized + DoubleEndedIterator,
2773 /// Converts an iterator of pairs into a pair of containers.
2775 /// `unzip()` consumes an entire iterator of pairs, producing two
2776 /// collections: one from the left elements of the pairs, and one
2777 /// from the right elements.
2779 /// This function is, in some sense, the opposite of [`zip`].
2781 /// [`zip`]: Iterator::zip
2788 /// let a = [(1, 2), (3, 4)];
2790 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2792 /// assert_eq!(left, [1, 3]);
2793 /// assert_eq!(right, [2, 4]);
2795 #[stable(feature = "rust1", since = "1.0.0")]
2796 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2798 FromA: Default + Extend<A>,
2799 FromB: Default + Extend<B>,
2800 Self: Sized + Iterator<Item = (A, B)>,
2802 fn extend<'a, A, B>(
2803 ts: &'a mut impl Extend<A>,
2804 us: &'a mut impl Extend<B>,
2805 ) -> impl FnMut((), (A, B)) + 'a {
2812 let mut ts: FromA = Default::default();
2813 let mut us: FromB = Default::default();
2815 let (lower_bound, _) = self.size_hint();
2816 if lower_bound > 0 {
2817 ts.extend_reserve(lower_bound);
2818 us.extend_reserve(lower_bound);
2821 self.fold((), extend(&mut ts, &mut us));
2826 /// Creates an iterator which copies all of its elements.
2828 /// This is useful when you have an iterator over `&T`, but you need an
2829 /// iterator over `T`.
2836 /// let a = [1, 2, 3];
2838 /// let v_copied: Vec<_> = a.iter().copied().collect();
2840 /// // copied is the same as .map(|&x| x)
2841 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2843 /// assert_eq!(v_copied, vec![1, 2, 3]);
2844 /// assert_eq!(v_map, vec![1, 2, 3]);
2846 #[stable(feature = "iter_copied", since = "1.36.0")]
2847 fn copied<'a, T: 'a>(self) -> Copied<Self>
2849 Self: Sized + Iterator<Item = &'a T>,
2855 /// Creates an iterator which [`clone`]s all of its elements.
2857 /// This is useful when you have an iterator over `&T`, but you need an
2858 /// iterator over `T`.
2860 /// [`clone`]: Clone::clone
2867 /// let a = [1, 2, 3];
2869 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2871 /// // cloned is the same as .map(|&x| x), for integers
2872 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2874 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2875 /// assert_eq!(v_map, vec![1, 2, 3]);
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2880 Self: Sized + Iterator<Item = &'a T>,
2886 /// Repeats an iterator endlessly.
2888 /// Instead of stopping at [`None`], the iterator will instead start again,
2889 /// from the beginning. After iterating again, it will start at the
2890 /// beginning again. And again. And again. Forever.
2897 /// let a = [1, 2, 3];
2899 /// let mut it = a.iter().cycle();
2901 /// assert_eq!(it.next(), Some(&1));
2902 /// assert_eq!(it.next(), Some(&2));
2903 /// assert_eq!(it.next(), Some(&3));
2904 /// assert_eq!(it.next(), Some(&1));
2905 /// assert_eq!(it.next(), Some(&2));
2906 /// assert_eq!(it.next(), Some(&3));
2907 /// assert_eq!(it.next(), Some(&1));
2909 #[stable(feature = "rust1", since = "1.0.0")]
2911 fn cycle(self) -> Cycle<Self>
2913 Self: Sized + Clone,
2918 /// Sums the elements of an iterator.
2920 /// Takes each element, adds them together, and returns the result.
2922 /// An empty iterator returns the zero value of the type.
2926 /// When calling `sum()` and a primitive integer type is being returned, this
2927 /// method will panic if the computation overflows and debug assertions are
2935 /// let a = [1, 2, 3];
2936 /// let sum: i32 = a.iter().sum();
2938 /// assert_eq!(sum, 6);
2940 #[stable(feature = "iter_arith", since = "1.11.0")]
2941 fn sum<S>(self) -> S
2949 /// Iterates over the entire iterator, multiplying all the elements
2951 /// An empty iterator returns the one value of the type.
2955 /// When calling `product()` and a primitive integer type is being returned,
2956 /// method will panic if the computation overflows and debug assertions are
2962 /// fn factorial(n: u32) -> u32 {
2963 /// (1..=n).product()
2965 /// assert_eq!(factorial(0), 1);
2966 /// assert_eq!(factorial(1), 1);
2967 /// assert_eq!(factorial(5), 120);
2969 #[stable(feature = "iter_arith", since = "1.11.0")]
2970 fn product<P>(self) -> P
2973 P: Product<Self::Item>,
2975 Product::product(self)
2978 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
2984 /// use std::cmp::Ordering;
2986 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2987 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2988 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2990 #[stable(feature = "iter_order", since = "1.5.0")]
2991 fn cmp<I>(self, other: I) -> Ordering
2993 I: IntoIterator<Item = Self::Item>,
2997 self.cmp_by(other, |x, y| x.cmp(&y))
3000 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3001 /// of another with respect to the specified comparison function.
3008 /// #![feature(iter_order_by)]
3010 /// use std::cmp::Ordering;
3012 /// let xs = [1, 2, 3, 4];
3013 /// let ys = [1, 4, 9, 16];
3015 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3016 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3017 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3019 #[unstable(feature = "iter_order_by", issue = "64295")]
3020 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
3024 F: FnMut(Self::Item, I::Item) -> Ordering,
3026 let mut other = other.into_iter();
3029 let x = match self.next() {
3031 if other.next().is_none() {
3032 return Ordering::Equal;
3034 return Ordering::Less;
3040 let y = match other.next() {
3041 None => return Ordering::Greater,
3046 Ordering::Equal => (),
3047 non_eq => return non_eq,
3052 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3058 /// use std::cmp::Ordering;
3060 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3061 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3062 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3064 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3066 #[stable(feature = "iter_order", since = "1.5.0")]
3067 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3070 Self::Item: PartialOrd<I::Item>,
3073 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3076 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3077 /// of another with respect to the specified comparison function.
3084 /// #![feature(iter_order_by)]
3086 /// use std::cmp::Ordering;
3088 /// let xs = [1.0, 2.0, 3.0, 4.0];
3089 /// let ys = [1.0, 4.0, 9.0, 16.0];
3092 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3093 /// Some(Ordering::Less)
3096 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3097 /// Some(Ordering::Equal)
3100 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3101 /// Some(Ordering::Greater)
3104 #[unstable(feature = "iter_order_by", issue = "64295")]
3105 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3109 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3111 let mut other = other.into_iter();
3114 let x = match self.next() {
3116 if other.next().is_none() {
3117 return Some(Ordering::Equal);
3119 return Some(Ordering::Less);
3125 let y = match other.next() {
3126 None => return Some(Ordering::Greater),
3130 match partial_cmp(x, y) {
3131 Some(Ordering::Equal) => (),
3132 non_eq => return non_eq,
3137 /// Determines if the elements of this [`Iterator`] are equal to those of
3143 /// assert_eq!([1].iter().eq([1].iter()), true);
3144 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3146 #[stable(feature = "iter_order", since = "1.5.0")]
3147 fn eq<I>(self, other: I) -> bool
3150 Self::Item: PartialEq<I::Item>,
3153 self.eq_by(other, |x, y| x == y)
3156 /// Determines if the elements of this [`Iterator`] are equal to those of
3157 /// another with respect to the specified equality function.
3164 /// #![feature(iter_order_by)]
3166 /// let xs = [1, 2, 3, 4];
3167 /// let ys = [1, 4, 9, 16];
3169 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3171 #[unstable(feature = "iter_order_by", issue = "64295")]
3172 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3176 F: FnMut(Self::Item, I::Item) -> bool,
3178 let mut other = other.into_iter();
3181 let x = match self.next() {
3182 None => return other.next().is_none(),
3186 let y = match other.next() {
3187 None => return false,
3197 /// Determines if the elements of this [`Iterator`] are unequal to those of
3203 /// assert_eq!([1].iter().ne([1].iter()), false);
3204 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3206 #[stable(feature = "iter_order", since = "1.5.0")]
3207 fn ne<I>(self, other: I) -> bool
3210 Self::Item: PartialEq<I::Item>,
3216 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3217 /// less than those of another.
3222 /// assert_eq!([1].iter().lt([1].iter()), false);
3223 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3224 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3225 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3227 #[stable(feature = "iter_order", since = "1.5.0")]
3228 fn lt<I>(self, other: I) -> bool
3231 Self::Item: PartialOrd<I::Item>,
3234 self.partial_cmp(other) == Some(Ordering::Less)
3237 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3238 /// less or equal to those of another.
3243 /// assert_eq!([1].iter().le([1].iter()), true);
3244 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3245 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3246 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3248 #[stable(feature = "iter_order", since = "1.5.0")]
3249 fn le<I>(self, other: I) -> bool
3252 Self::Item: PartialOrd<I::Item>,
3255 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3258 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3259 /// greater than those of another.
3264 /// assert_eq!([1].iter().gt([1].iter()), false);
3265 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3266 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3267 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3269 #[stable(feature = "iter_order", since = "1.5.0")]
3270 fn gt<I>(self, other: I) -> bool
3273 Self::Item: PartialOrd<I::Item>,
3276 self.partial_cmp(other) == Some(Ordering::Greater)
3279 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3280 /// greater than or equal to those of another.
3285 /// assert_eq!([1].iter().ge([1].iter()), true);
3286 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3287 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3288 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3290 #[stable(feature = "iter_order", since = "1.5.0")]
3291 fn ge<I>(self, other: I) -> bool
3294 Self::Item: PartialOrd<I::Item>,
3297 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3300 /// Checks if the elements of this iterator are sorted.
3302 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3303 /// iterator yields exactly zero or one element, `true` is returned.
3305 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3306 /// implies that this function returns `false` if any two consecutive items are not
3312 /// #![feature(is_sorted)]
3314 /// assert!([1, 2, 2, 9].iter().is_sorted());
3315 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3316 /// assert!([0].iter().is_sorted());
3317 /// assert!(std::iter::empty::<i32>().is_sorted());
3318 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3321 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3322 fn is_sorted(self) -> bool
3325 Self::Item: PartialOrd,
3327 self.is_sorted_by(PartialOrd::partial_cmp)
3330 /// Checks if the elements of this iterator are sorted using the given comparator function.
3332 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3333 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3334 /// [`is_sorted`]; see its documentation for more information.
3339 /// #![feature(is_sorted)]
3341 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3342 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3343 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3344 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3345 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3348 /// [`is_sorted`]: Iterator::is_sorted
3349 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3350 fn is_sorted_by<F>(mut self, compare: F) -> bool
3353 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3358 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3359 ) -> impl FnMut(T) -> bool + 'a {
3361 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3369 let mut last = match self.next() {
3371 None => return true,
3374 self.all(check(&mut last, compare))
3377 /// Checks if the elements of this iterator are sorted using the given key extraction
3380 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3381 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3382 /// its documentation for more information.
3384 /// [`is_sorted`]: Iterator::is_sorted
3389 /// #![feature(is_sorted)]
3391 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3392 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3395 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3396 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3399 F: FnMut(Self::Item) -> K,
3402 self.map(f).is_sorted()
3405 /// See [TrustedRandomAccess]
3406 // The unusual name is to avoid name collisions in method resolution
3410 #[unstable(feature = "trusted_random_access", issue = "none")]
3411 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3413 Self: TrustedRandomAccess,
3415 unreachable!("Always specialized");
3419 #[stable(feature = "rust1", since = "1.0.0")]
3420 impl<I: Iterator + ?Sized> Iterator for &mut I {
3421 type Item = I::Item;
3422 fn next(&mut self) -> Option<I::Item> {
3425 fn size_hint(&self) -> (usize, Option<usize>) {
3426 (**self).size_hint()
3428 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3429 (**self).advance_by(n)
3431 fn nth(&mut self, n: usize) -> Option<Self::Item> {