1 // ignore-tidy-filelength
2 // This file almost exclusively consists of the definition of `Iterator`. We
3 // can't split that into multiple files.
5 use crate::cmp::{self, Ordering};
6 use crate::ops::{Add, Try};
8 use super::super::LoopState;
9 use super::super::TrustedRandomAccess;
10 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
11 use super::super::{FlatMap, Flatten};
12 use super::super::{FromIterator, Product, Sum, Zip};
14 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
17 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
19 /// An interface for dealing with iterators.
21 /// This is the main iterator trait. For more about the concept of iterators
22 /// generally, please see the [module-level documentation]. In particular, you
23 /// may want to know how to [implement `Iterator`][impl].
25 /// [module-level documentation]: index.html
26 /// [impl]: index.html#implementing-iterator
27 #[stable(feature = "rust1", since = "1.0.0")]
28 #[rustc_on_unimplemented(
30 _Self = "[std::ops::Range<Idx>; 1]",
31 label = "if you meant to iterate between two values, remove the square brackets",
32 note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
33 without the brackets: `start..end`"
36 _Self = "[std::ops::RangeFrom<Idx>; 1]",
37 label = "if you meant to iterate from a value onwards, remove the square brackets",
38 note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
39 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
40 unbounded iterator will run forever unless you `break` or `return` from within the \
44 _Self = "[std::ops::RangeTo<Idx>; 1]",
45 label = "if you meant to iterate until a value, remove the square brackets and add a \
47 note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
48 `Range` without the brackets: `0..end`"
51 _Self = "[std::ops::RangeInclusive<Idx>; 1]",
52 label = "if you meant to iterate between two values, remove the square brackets",
53 note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
54 `RangeInclusive` without the brackets: `start..=end`"
57 _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
58 label = "if you meant to iterate until a value (including it), remove the square brackets \
59 and add a starting value",
60 note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
61 bounded `RangeInclusive` without the brackets: `0..=end`"
64 _Self = "std::ops::RangeTo<Idx>",
65 label = "if you meant to iterate until a value, add a starting value",
66 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
67 bounded `Range`: `0..end`"
70 _Self = "std::ops::RangeToInclusive<Idx>",
71 label = "if you meant to iterate until a value (including it), add a starting value",
72 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
73 to have a bounded `RangeInclusive`: `0..=end`"
77 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
80 _Self = "std::string::String",
81 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
85 label = "borrow the array with `&` or call `.iter()` on it to iterate over it",
86 note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
90 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
91 syntax `start..end` or the inclusive range syntax `start..=end`"
93 label = "`{Self}` is not an iterator",
94 message = "`{Self}` is not an iterator"
97 #[must_use = "iterators are lazy and do nothing unless consumed"]
99 /// The type of the elements being iterated over.
100 #[stable(feature = "rust1", since = "1.0.0")]
103 /// Advances the iterator and returns the next value.
105 /// Returns [`None`] when iteration is finished. Individual iterator
106 /// implementations may choose to resume iteration, and so calling `next()`
107 /// again may or may not eventually start returning [`Some(Item)`] again at some
110 /// [`Some(Item)`]: Some
117 /// let a = [1, 2, 3];
119 /// let mut iter = a.iter();
121 /// // A call to next() returns the next value...
122 /// assert_eq!(Some(&1), iter.next());
123 /// assert_eq!(Some(&2), iter.next());
124 /// assert_eq!(Some(&3), iter.next());
126 /// // ... and then None once it's over.
127 /// assert_eq!(None, iter.next());
129 /// // More calls may or may not return `None`. Here, they always will.
130 /// assert_eq!(None, iter.next());
131 /// assert_eq!(None, iter.next());
134 #[stable(feature = "rust1", since = "1.0.0")]
135 fn next(&mut self) -> Option<Self::Item>;
137 /// Returns the bounds on the remaining length of the iterator.
139 /// Specifically, `size_hint()` returns a tuple where the first element
140 /// is the lower bound, and the second element is the upper bound.
142 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
143 /// A [`None`] here means that either there is no known upper bound, or the
144 /// upper bound is larger than [`usize`].
146 /// # Implementation notes
148 /// It is not enforced that an iterator implementation yields the declared
149 /// number of elements. A buggy iterator may yield less than the lower bound
150 /// or more than the upper bound of elements.
152 /// `size_hint()` is primarily intended to be used for optimizations such as
153 /// reserving space for the elements of the iterator, but must not be
154 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
155 /// implementation of `size_hint()` should not lead to memory safety
158 /// That said, the implementation should provide a correct estimation,
159 /// because otherwise it would be a violation of the trait's protocol.
161 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
164 /// [`usize`]: type@usize
171 /// let a = [1, 2, 3];
172 /// let iter = a.iter();
174 /// assert_eq!((3, Some(3)), iter.size_hint());
177 /// A more complex example:
180 /// // The even numbers from zero to ten.
181 /// let iter = (0..10).filter(|x| x % 2 == 0);
183 /// // We might iterate from zero to ten times. Knowing that it's five
184 /// // exactly wouldn't be possible without executing filter().
185 /// assert_eq!((0, Some(10)), iter.size_hint());
187 /// // Let's add five more numbers with chain()
188 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
190 /// // now both bounds are increased by five
191 /// assert_eq!((5, Some(15)), iter.size_hint());
194 /// Returning `None` for an upper bound:
197 /// // an infinite iterator has no upper bound
198 /// // and the maximum possible lower bound
201 /// assert_eq!((usize::MAX, None), iter.size_hint());
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn size_hint(&self) -> (usize, Option<usize>) {
209 /// Consumes the iterator, counting the number of iterations and returning it.
211 /// This method will call [`next`] repeatedly until [`None`] is encountered,
212 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213 /// called at least once even if the iterator does not have any elements.
215 /// [`next`]: #tymethod.next
217 /// # Overflow Behavior
219 /// The method does no guarding against overflows, so counting elements of
220 /// an iterator with more than [`usize::MAX`] elements either produces the
221 /// wrong result or panics. If debug assertions are enabled, a panic is
226 /// This function might panic if the iterator has more than [`usize::MAX`]
229 /// [`usize::MAX`]: crate::usize::MAX
236 /// let a = [1, 2, 3];
237 /// assert_eq!(a.iter().count(), 3);
239 /// let a = [1, 2, 3, 4, 5];
240 /// assert_eq!(a.iter().count(), 5);
243 #[stable(feature = "rust1", since = "1.0.0")]
244 fn count(self) -> usize
249 fn add1<T>(count: usize, _: T) -> usize {
257 /// Consumes the iterator, returning the last element.
259 /// This method will evaluate the iterator until it returns [`None`]. While
260 /// doing so, it keeps track of the current element. After [`None`] is
261 /// returned, `last()` will then return the last element it saw.
268 /// let a = [1, 2, 3];
269 /// assert_eq!(a.iter().last(), Some(&3));
271 /// let a = [1, 2, 3, 4, 5];
272 /// assert_eq!(a.iter().last(), Some(&5));
275 #[stable(feature = "rust1", since = "1.0.0")]
276 fn last(self) -> Option<Self::Item>
281 fn some<T>(_: Option<T>, x: T) -> Option<T> {
285 self.fold(None, some)
288 /// Returns the `n`th element of the iterator.
290 /// Like most indexing operations, the count starts from zero, so `nth(0)`
291 /// returns the first value, `nth(1)` the second, and so on.
293 /// Note that all preceding elements, as well as the returned element, will be
294 /// consumed from the iterator. That means that the preceding elements will be
295 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
296 /// will return different elements.
298 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
306 /// let a = [1, 2, 3];
307 /// assert_eq!(a.iter().nth(1), Some(&2));
310 /// Calling `nth()` multiple times doesn't rewind the iterator:
313 /// let a = [1, 2, 3];
315 /// let mut iter = a.iter();
317 /// assert_eq!(iter.nth(1), Some(&2));
318 /// assert_eq!(iter.nth(1), None);
321 /// Returning `None` if there are less than `n + 1` elements:
324 /// let a = [1, 2, 3];
325 /// assert_eq!(a.iter().nth(10), None);
328 #[stable(feature = "rust1", since = "1.0.0")]
329 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
330 while let Some(x) = self.next() {
339 /// Creates an iterator starting at the same point, but stepping by
340 /// the given amount at each iteration.
342 /// Note 1: The first element of the iterator will always be returned,
343 /// regardless of the step given.
345 /// Note 2: The time at which ignored elements are pulled is not fixed.
346 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
347 /// but is also free to behave like the sequence
348 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
349 /// Which way is used may change for some iterators for performance reasons.
350 /// The second way will advance the iterator earlier and may consume more items.
352 /// `advance_n_and_return_first` is the equivalent of:
354 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
358 /// let next = iter.next();
359 /// if total_step > 1 {
360 /// iter.nth(total_step-2);
368 /// The method will panic if the given step is `0`.
375 /// let a = [0, 1, 2, 3, 4, 5];
376 /// let mut iter = a.iter().step_by(2);
378 /// assert_eq!(iter.next(), Some(&0));
379 /// assert_eq!(iter.next(), Some(&2));
380 /// assert_eq!(iter.next(), Some(&4));
381 /// assert_eq!(iter.next(), None);
384 #[stable(feature = "iterator_step_by", since = "1.28.0")]
385 fn step_by(self, step: usize) -> StepBy<Self>
389 StepBy::new(self, step)
392 /// Takes two iterators and creates a new iterator over both in sequence.
394 /// `chain()` will return a new iterator which will first iterate over
395 /// values from the first iterator and then over values from the second
398 /// In other words, it links two iterators together, in a chain. 🔗
400 /// [`once`] is commonly used to adapt a single value into a chain of
401 /// other kinds of iteration.
408 /// let a1 = [1, 2, 3];
409 /// let a2 = [4, 5, 6];
411 /// let mut iter = a1.iter().chain(a2.iter());
413 /// assert_eq!(iter.next(), Some(&1));
414 /// assert_eq!(iter.next(), Some(&2));
415 /// assert_eq!(iter.next(), Some(&3));
416 /// assert_eq!(iter.next(), Some(&4));
417 /// assert_eq!(iter.next(), Some(&5));
418 /// assert_eq!(iter.next(), Some(&6));
419 /// assert_eq!(iter.next(), None);
422 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
423 /// anything that can be converted into an [`Iterator`], not just an
424 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
425 /// [`IntoIterator`], and so can be passed to `chain()` directly:
428 /// let s1 = &[1, 2, 3];
429 /// let s2 = &[4, 5, 6];
431 /// let mut iter = s1.iter().chain(s2);
433 /// assert_eq!(iter.next(), Some(&1));
434 /// assert_eq!(iter.next(), Some(&2));
435 /// assert_eq!(iter.next(), Some(&3));
436 /// assert_eq!(iter.next(), Some(&4));
437 /// assert_eq!(iter.next(), Some(&5));
438 /// assert_eq!(iter.next(), Some(&6));
439 /// assert_eq!(iter.next(), None);
442 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
446 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
447 /// use std::os::windows::ffi::OsStrExt;
448 /// s.encode_wide().chain(std::iter::once(0)).collect()
452 /// [`once`]: fn.once.html
453 /// [`Iterator`]: trait.Iterator.html
454 /// [`IntoIterator`]: trait.IntoIterator.html
455 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
457 #[stable(feature = "rust1", since = "1.0.0")]
458 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
461 U: IntoIterator<Item = Self::Item>,
463 Chain::new(self, other.into_iter())
466 /// 'Zips up' two iterators into a single iterator of pairs.
468 /// `zip()` returns a new iterator that will iterate over two other
469 /// iterators, returning a tuple where the first element comes from the
470 /// first iterator, and the second element comes from the second iterator.
472 /// In other words, it zips two iterators together, into a single one.
474 /// If either iterator returns [`None`], [`next`] from the zipped iterator
475 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
476 /// short-circuit and `next` will not be called on the second iterator.
483 /// let a1 = [1, 2, 3];
484 /// let a2 = [4, 5, 6];
486 /// let mut iter = a1.iter().zip(a2.iter());
488 /// assert_eq!(iter.next(), Some((&1, &4)));
489 /// assert_eq!(iter.next(), Some((&2, &5)));
490 /// assert_eq!(iter.next(), Some((&3, &6)));
491 /// assert_eq!(iter.next(), None);
494 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
495 /// anything that can be converted into an [`Iterator`], not just an
496 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
497 /// [`IntoIterator`], and so can be passed to `zip()` directly:
499 /// [`IntoIterator`]: trait.IntoIterator.html
500 /// [`Iterator`]: trait.Iterator.html
503 /// let s1 = &[1, 2, 3];
504 /// let s2 = &[4, 5, 6];
506 /// let mut iter = s1.iter().zip(s2);
508 /// assert_eq!(iter.next(), Some((&1, &4)));
509 /// assert_eq!(iter.next(), Some((&2, &5)));
510 /// assert_eq!(iter.next(), Some((&3, &6)));
511 /// assert_eq!(iter.next(), None);
514 /// `zip()` is often used to zip an infinite iterator to a finite one.
515 /// This works because the finite iterator will eventually return [`None`],
516 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
519 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
521 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
523 /// assert_eq!((0, 'f'), enumerate[0]);
524 /// assert_eq!((0, 'f'), zipper[0]);
526 /// assert_eq!((1, 'o'), enumerate[1]);
527 /// assert_eq!((1, 'o'), zipper[1]);
529 /// assert_eq!((2, 'o'), enumerate[2]);
530 /// assert_eq!((2, 'o'), zipper[2]);
533 /// [`enumerate`]: #method.enumerate
534 /// [`next`]: #tymethod.next
536 #[stable(feature = "rust1", since = "1.0.0")]
537 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
542 Zip::new(self, other.into_iter())
545 /// Takes a closure and creates an iterator which calls that closure on each
548 /// `map()` transforms one iterator into another, by means of its argument:
549 /// something that implements [`FnMut`]. It produces a new iterator which
550 /// calls this closure on each element of the original iterator.
552 /// If you are good at thinking in types, you can think of `map()` like this:
553 /// If you have an iterator that gives you elements of some type `A`, and
554 /// you want an iterator of some other type `B`, you can use `map()`,
555 /// passing a closure that takes an `A` and returns a `B`.
557 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
558 /// lazy, it is best used when you're already working with other iterators.
559 /// If you're doing some sort of looping for a side effect, it's considered
560 /// more idiomatic to use [`for`] than `map()`.
562 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
563 /// [`FnMut`]: crate::ops::FnMut
570 /// let a = [1, 2, 3];
572 /// let mut iter = a.iter().map(|x| 2 * x);
574 /// assert_eq!(iter.next(), Some(2));
575 /// assert_eq!(iter.next(), Some(4));
576 /// assert_eq!(iter.next(), Some(6));
577 /// assert_eq!(iter.next(), None);
580 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
583 /// # #![allow(unused_must_use)]
584 /// // don't do this:
585 /// (0..5).map(|x| println!("{}", x));
587 /// // it won't even execute, as it is lazy. Rust will warn you about this.
589 /// // Instead, use for:
591 /// println!("{}", x);
595 #[stable(feature = "rust1", since = "1.0.0")]
596 fn map<B, F>(self, f: F) -> Map<Self, F>
599 F: FnMut(Self::Item) -> B,
604 /// Calls a closure on each element of an iterator.
606 /// This is equivalent to using a [`for`] loop on the iterator, although
607 /// `break` and `continue` are not possible from a closure. It's generally
608 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
609 /// when processing items at the end of longer iterator chains. In some
610 /// cases `for_each` may also be faster than a loop, because it will use
611 /// internal iteration on adaptors like `Chain`.
613 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
620 /// use std::sync::mpsc::channel;
622 /// let (tx, rx) = channel();
623 /// (0..5).map(|x| x * 2 + 1)
624 /// .for_each(move |x| tx.send(x).unwrap());
626 /// let v: Vec<_> = rx.iter().collect();
627 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
630 /// For such a small example, a `for` loop may be cleaner, but `for_each`
631 /// might be preferable to keep a functional style with longer iterators:
634 /// (0..5).flat_map(|x| x * 100 .. x * 110)
636 /// .filter(|&(i, x)| (i + x) % 3 == 0)
637 /// .for_each(|(i, x)| println!("{}:{}", i, x));
640 #[stable(feature = "iterator_for_each", since = "1.21.0")]
641 fn for_each<F>(self, f: F)
644 F: FnMut(Self::Item),
647 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
648 move |(), item| f(item)
651 self.fold((), call(f));
654 /// Creates an iterator which uses a closure to determine if an element
655 /// should be yielded.
657 /// The closure must return `true` or `false`. `filter()` creates an
658 /// iterator which calls this closure on each element. If the closure
659 /// returns `true`, then the element is returned. If the closure returns
660 /// `false`, it will try again, and call the closure on the next element,
661 /// seeing if it passes the test.
668 /// let a = [0i32, 1, 2];
670 /// let mut iter = a.iter().filter(|x| x.is_positive());
672 /// assert_eq!(iter.next(), Some(&1));
673 /// assert_eq!(iter.next(), Some(&2));
674 /// assert_eq!(iter.next(), None);
677 /// Because the closure passed to `filter()` takes a reference, and many
678 /// iterators iterate over references, this leads to a possibly confusing
679 /// situation, where the type of the closure is a double reference:
682 /// let a = [0, 1, 2];
684 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
686 /// assert_eq!(iter.next(), Some(&2));
687 /// assert_eq!(iter.next(), None);
690 /// It's common to instead use destructuring on the argument to strip away
694 /// let a = [0, 1, 2];
696 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
698 /// assert_eq!(iter.next(), Some(&2));
699 /// assert_eq!(iter.next(), None);
705 /// let a = [0, 1, 2];
707 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
709 /// assert_eq!(iter.next(), Some(&2));
710 /// assert_eq!(iter.next(), None);
715 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
717 #[stable(feature = "rust1", since = "1.0.0")]
718 fn filter<P>(self, predicate: P) -> Filter<Self, P>
721 P: FnMut(&Self::Item) -> bool,
723 Filter::new(self, predicate)
726 /// Creates an iterator that both filters and maps.
728 /// The closure must return an [`Option<T>`]. `filter_map` creates an
729 /// iterator which calls this closure on each element. If the closure
730 /// returns [`Some(element)`][`Some`], then that element is returned. If the
731 /// closure returns [`None`], it will try again, and call the closure on the
732 /// next element, seeing if it will return [`Some`].
734 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
737 /// [`filter`]: #method.filter
738 /// [`map`]: #method.map
740 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
742 /// In other words, it removes the [`Option<T>`] layer automatically. If your
743 /// mapping is already returning an [`Option<T>`] and you want to skip over
744 /// [`None`]s, then `filter_map` is much, much nicer to use.
751 /// let a = ["1", "two", "NaN", "four", "5"];
753 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
755 /// assert_eq!(iter.next(), Some(1));
756 /// assert_eq!(iter.next(), Some(5));
757 /// assert_eq!(iter.next(), None);
760 /// Here's the same example, but with [`filter`] and [`map`]:
763 /// let a = ["1", "two", "NaN", "four", "5"];
764 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
765 /// assert_eq!(iter.next(), Some(1));
766 /// assert_eq!(iter.next(), Some(5));
767 /// assert_eq!(iter.next(), None);
770 /// [`Option<T>`]: Option
772 #[stable(feature = "rust1", since = "1.0.0")]
773 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
776 F: FnMut(Self::Item) -> Option<B>,
778 FilterMap::new(self, f)
781 /// Creates an iterator which gives the current iteration count as well as
784 /// The iterator returned yields pairs `(i, val)`, where `i` is the
785 /// current index of iteration and `val` is the value returned by the
788 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
789 /// different sized integer, the [`zip`] function provides similar
792 /// # Overflow Behavior
794 /// The method does no guarding against overflows, so enumerating more than
795 /// [`usize::MAX`] elements either produces the wrong result or panics. If
796 /// debug assertions are enabled, a panic is guaranteed.
800 /// The returned iterator might panic if the to-be-returned index would
801 /// overflow a [`usize`].
803 /// [`usize`]: type@usize
804 /// [`usize::MAX`]: crate::usize::MAX
805 /// [`zip`]: #method.zip
810 /// let a = ['a', 'b', 'c'];
812 /// let mut iter = a.iter().enumerate();
814 /// assert_eq!(iter.next(), Some((0, &'a')));
815 /// assert_eq!(iter.next(), Some((1, &'b')));
816 /// assert_eq!(iter.next(), Some((2, &'c')));
817 /// assert_eq!(iter.next(), None);
820 #[stable(feature = "rust1", since = "1.0.0")]
821 fn enumerate(self) -> Enumerate<Self>
828 /// Creates an iterator which can use `peek` to look at the next element of
829 /// the iterator without consuming it.
831 /// Adds a [`peek`] method to an iterator. See its documentation for
832 /// more information.
834 /// Note that the underlying iterator is still advanced when [`peek`] is
835 /// called for the first time: In order to retrieve the next element,
836 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
837 /// anything other than fetching the next value) of the [`next`] method
840 /// [`peek`]: crate::iter::Peekable::peek
841 /// [`next`]: #tymethod.next
848 /// let xs = [1, 2, 3];
850 /// let mut iter = xs.iter().peekable();
852 /// // peek() lets us see into the future
853 /// assert_eq!(iter.peek(), Some(&&1));
854 /// assert_eq!(iter.next(), Some(&1));
856 /// assert_eq!(iter.next(), Some(&2));
858 /// // we can peek() multiple times, the iterator won't advance
859 /// assert_eq!(iter.peek(), Some(&&3));
860 /// assert_eq!(iter.peek(), Some(&&3));
862 /// assert_eq!(iter.next(), Some(&3));
864 /// // after the iterator is finished, so is peek()
865 /// assert_eq!(iter.peek(), None);
866 /// assert_eq!(iter.next(), None);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 fn peekable(self) -> Peekable<Self>
877 /// Creates an iterator that [`skip`]s elements based on a predicate.
879 /// [`skip`]: #method.skip
881 /// `skip_while()` takes a closure as an argument. It will call this
882 /// closure on each element of the iterator, and ignore elements
883 /// until it returns `false`.
885 /// After `false` is returned, `skip_while()`'s job is over, and the
886 /// rest of the elements are yielded.
893 /// let a = [-1i32, 0, 1];
895 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
897 /// assert_eq!(iter.next(), Some(&0));
898 /// assert_eq!(iter.next(), Some(&1));
899 /// assert_eq!(iter.next(), None);
902 /// Because the closure passed to `skip_while()` takes a reference, and many
903 /// iterators iterate over references, this leads to a possibly confusing
904 /// situation, where the type of the closure is a double reference:
907 /// let a = [-1, 0, 1];
909 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
911 /// assert_eq!(iter.next(), Some(&0));
912 /// assert_eq!(iter.next(), Some(&1));
913 /// assert_eq!(iter.next(), None);
916 /// Stopping after an initial `false`:
919 /// let a = [-1, 0, 1, -2];
921 /// let mut iter = a.iter().skip_while(|x| **x < 0);
923 /// assert_eq!(iter.next(), Some(&0));
924 /// assert_eq!(iter.next(), Some(&1));
926 /// // while this would have been false, since we already got a false,
927 /// // skip_while() isn't used any more
928 /// assert_eq!(iter.next(), Some(&-2));
930 /// assert_eq!(iter.next(), None);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
937 P: FnMut(&Self::Item) -> bool,
939 SkipWhile::new(self, predicate)
942 /// Creates an iterator that yields elements based on a predicate.
944 /// `take_while()` takes a closure as an argument. It will call this
945 /// closure on each element of the iterator, and yield elements
946 /// while it returns `true`.
948 /// After `false` is returned, `take_while()`'s job is over, and the
949 /// rest of the elements are ignored.
956 /// let a = [-1i32, 0, 1];
958 /// let mut iter = a.iter().take_while(|x| x.is_negative());
960 /// assert_eq!(iter.next(), Some(&-1));
961 /// assert_eq!(iter.next(), None);
964 /// Because the closure passed to `take_while()` takes a reference, and many
965 /// iterators iterate over references, this leads to a possibly confusing
966 /// situation, where the type of the closure is a double reference:
969 /// let a = [-1, 0, 1];
971 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
973 /// assert_eq!(iter.next(), Some(&-1));
974 /// assert_eq!(iter.next(), None);
977 /// Stopping after an initial `false`:
980 /// let a = [-1, 0, 1, -2];
982 /// let mut iter = a.iter().take_while(|x| **x < 0);
984 /// assert_eq!(iter.next(), Some(&-1));
986 /// // We have more elements that are less than zero, but since we already
987 /// // got a false, take_while() isn't used any more
988 /// assert_eq!(iter.next(), None);
991 /// Because `take_while()` needs to look at the value in order to see if it
992 /// should be included or not, consuming iterators will see that it is
996 /// let a = [1, 2, 3, 4];
997 /// let mut iter = a.iter();
999 /// let result: Vec<i32> = iter.by_ref()
1000 /// .take_while(|n| **n != 3)
1004 /// assert_eq!(result, &[1, 2]);
1006 /// let result: Vec<i32> = iter.cloned().collect();
1008 /// assert_eq!(result, &[4]);
1011 /// The `3` is no longer there, because it was consumed in order to see if
1012 /// the iteration should stop, but wasn't placed back into the iterator.
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1018 P: FnMut(&Self::Item) -> bool,
1020 TakeWhile::new(self, predicate)
1023 /// Creates an iterator that both yields elements based on a predicate and maps.
1025 /// `map_while()` takes a closure as an argument. It will call this
1026 /// closure on each element of the iterator, and yield elements
1027 /// while it returns [`Some(_)`][`Some`].
1034 /// #![feature(iter_map_while)]
1035 /// let a = [-1i32, 4, 0, 1];
1037 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1039 /// assert_eq!(iter.next(), Some(-16));
1040 /// assert_eq!(iter.next(), Some(4));
1041 /// assert_eq!(iter.next(), None);
1044 /// Here's the same example, but with [`take_while`] and [`map`]:
1046 /// [`take_while`]: #method.take_while
1047 /// [`map`]: #method.map
1050 /// let a = [-1i32, 4, 0, 1];
1052 /// let mut iter = a.iter()
1053 /// .map(|x| 16i32.checked_div(*x))
1054 /// .take_while(|x| x.is_some())
1055 /// .map(|x| x.unwrap());
1057 /// assert_eq!(iter.next(), Some(-16));
1058 /// assert_eq!(iter.next(), Some(4));
1059 /// assert_eq!(iter.next(), None);
1062 /// Stopping after an initial [`None`]:
1065 /// #![feature(iter_map_while)]
1066 /// use std::convert::TryFrom;
1068 /// let a = [0, 1, 2, -3, 4, 5, -6];
1070 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1071 /// let vec = iter.collect::<Vec<_>>();
1073 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1074 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1075 /// assert_eq!(vec, vec![0, 1, 2]);
1078 /// Because `map_while()` needs to look at the value in order to see if it
1079 /// should be included or not, consuming iterators will see that it is
1083 /// #![feature(iter_map_while)]
1084 /// use std::convert::TryFrom;
1086 /// let a = [1, 2, -3, 4];
1087 /// let mut iter = a.iter();
1089 /// let result: Vec<u32> = iter.by_ref()
1090 /// .map_while(|n| u32::try_from(*n).ok())
1093 /// assert_eq!(result, &[1, 2]);
1095 /// let result: Vec<i32> = iter.cloned().collect();
1097 /// assert_eq!(result, &[4]);
1100 /// The `-3` is no longer there, because it was consumed in order to see if
1101 /// the iteration should stop, but wasn't placed back into the iterator.
1103 /// Note that unlike [`take_while`] this iterator is **not** fused.
1104 /// It is also not specified what this iterator returns after the first` None` is returned.
1105 /// If you need fused iterator, use [`fuse`].
1107 /// [`fuse`]: #method.fuse
1109 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1110 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1113 P: FnMut(Self::Item) -> Option<B>,
1115 MapWhile::new(self, predicate)
1118 /// Creates an iterator that skips the first `n` elements.
1120 /// After they have been consumed, the rest of the elements are yielded.
1121 /// Rather than overriding this method directly, instead override the `nth` method.
1128 /// let a = [1, 2, 3];
1130 /// let mut iter = a.iter().skip(2);
1132 /// assert_eq!(iter.next(), Some(&3));
1133 /// assert_eq!(iter.next(), None);
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 fn skip(self, n: usize) -> Skip<Self>
1144 /// Creates an iterator that yields its first `n` elements.
1151 /// let a = [1, 2, 3];
1153 /// let mut iter = a.iter().take(2);
1155 /// assert_eq!(iter.next(), Some(&1));
1156 /// assert_eq!(iter.next(), Some(&2));
1157 /// assert_eq!(iter.next(), None);
1160 /// `take()` is often used with an infinite iterator, to make it finite:
1163 /// let mut iter = (0..).take(3);
1165 /// assert_eq!(iter.next(), Some(0));
1166 /// assert_eq!(iter.next(), Some(1));
1167 /// assert_eq!(iter.next(), Some(2));
1168 /// assert_eq!(iter.next(), None);
1171 /// If less than `n` elements are available,
1172 /// `take` will limit itself to the size of the underlying iterator:
1175 /// let v = vec![1, 2];
1176 /// let mut iter = v.into_iter().take(5);
1177 /// assert_eq!(iter.next(), Some(1));
1178 /// assert_eq!(iter.next(), Some(2));
1179 /// assert_eq!(iter.next(), None);
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 fn take(self, n: usize) -> Take<Self>
1190 /// An iterator adaptor similar to [`fold`] that holds internal state and
1191 /// produces a new iterator.
1193 /// [`fold`]: #method.fold
1195 /// `scan()` takes two arguments: an initial value which seeds the internal
1196 /// state, and a closure with two arguments, the first being a mutable
1197 /// reference to the internal state and the second an iterator element.
1198 /// The closure can assign to the internal state to share state between
1201 /// On iteration, the closure will be applied to each element of the
1202 /// iterator and the return value from the closure, an [`Option`], is
1203 /// yielded by the iterator.
1210 /// let a = [1, 2, 3];
1212 /// let mut iter = a.iter().scan(1, |state, &x| {
1213 /// // each iteration, we'll multiply the state by the element
1214 /// *state = *state * x;
1216 /// // then, we'll yield the negation of the state
1220 /// assert_eq!(iter.next(), Some(-1));
1221 /// assert_eq!(iter.next(), Some(-2));
1222 /// assert_eq!(iter.next(), Some(-6));
1223 /// assert_eq!(iter.next(), None);
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1230 F: FnMut(&mut St, Self::Item) -> Option<B>,
1232 Scan::new(self, initial_state, f)
1235 /// Creates an iterator that works like map, but flattens nested structure.
1237 /// The [`map`] adapter is very useful, but only when the closure
1238 /// argument produces values. If it produces an iterator instead, there's
1239 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1242 /// You can think of `flat_map(f)` as the semantic equivalent
1243 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1245 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1246 /// one item for each element, and `flat_map()`'s closure returns an
1247 /// iterator for each element.
1249 /// [`map`]: #method.map
1250 /// [`flatten`]: #method.flatten
1257 /// let words = ["alpha", "beta", "gamma"];
1259 /// // chars() returns an iterator
1260 /// let merged: String = words.iter()
1261 /// .flat_map(|s| s.chars())
1263 /// assert_eq!(merged, "alphabetagamma");
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1271 F: FnMut(Self::Item) -> U,
1273 FlatMap::new(self, f)
1276 /// Creates an iterator that flattens nested structure.
1278 /// This is useful when you have an iterator of iterators or an iterator of
1279 /// things that can be turned into iterators and you want to remove one
1280 /// level of indirection.
1287 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1288 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1289 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1292 /// Mapping and then flattening:
1295 /// let words = ["alpha", "beta", "gamma"];
1297 /// // chars() returns an iterator
1298 /// let merged: String = words.iter()
1299 /// .map(|s| s.chars())
1302 /// assert_eq!(merged, "alphabetagamma");
1305 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1306 /// in this case since it conveys intent more clearly:
1309 /// let words = ["alpha", "beta", "gamma"];
1311 /// // chars() returns an iterator
1312 /// let merged: String = words.iter()
1313 /// .flat_map(|s| s.chars())
1315 /// assert_eq!(merged, "alphabetagamma");
1318 /// Flattening once only removes one level of nesting:
1321 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1323 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1324 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1326 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1327 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1330 /// Here we see that `flatten()` does not perform a "deep" flatten.
1331 /// Instead, only one level of nesting is removed. That is, if you
1332 /// `flatten()` a three-dimensional array the result will be
1333 /// two-dimensional and not one-dimensional. To get a one-dimensional
1334 /// structure, you have to `flatten()` again.
1336 /// [`flat_map()`]: #method.flat_map
1338 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1339 fn flatten(self) -> Flatten<Self>
1342 Self::Item: IntoIterator,
1347 /// Creates an iterator which ends after the first [`None`].
1349 /// After an iterator returns [`None`], future calls may or may not yield
1350 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1351 /// [`None`] is given, it will always return [`None`] forever.
1353 /// [`Some(T)`]: Some
1360 /// // an iterator which alternates between Some and None
1361 /// struct Alternate {
1365 /// impl Iterator for Alternate {
1366 /// type Item = i32;
1368 /// fn next(&mut self) -> Option<i32> {
1369 /// let val = self.state;
1370 /// self.state = self.state + 1;
1372 /// // if it's even, Some(i32), else None
1373 /// if val % 2 == 0 {
1381 /// let mut iter = Alternate { state: 0 };
1383 /// // we can see our iterator going back and forth
1384 /// assert_eq!(iter.next(), Some(0));
1385 /// assert_eq!(iter.next(), None);
1386 /// assert_eq!(iter.next(), Some(2));
1387 /// assert_eq!(iter.next(), None);
1389 /// // however, once we fuse it...
1390 /// let mut iter = iter.fuse();
1392 /// assert_eq!(iter.next(), Some(4));
1393 /// assert_eq!(iter.next(), None);
1395 /// // it will always return `None` after the first time.
1396 /// assert_eq!(iter.next(), None);
1397 /// assert_eq!(iter.next(), None);
1398 /// assert_eq!(iter.next(), None);
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 fn fuse(self) -> Fuse<Self>
1409 /// Does something with each element of an iterator, passing the value on.
1411 /// When using iterators, you'll often chain several of them together.
1412 /// While working on such code, you might want to check out what's
1413 /// happening at various parts in the pipeline. To do that, insert
1414 /// a call to `inspect()`.
1416 /// It's more common for `inspect()` to be used as a debugging tool than to
1417 /// exist in your final code, but applications may find it useful in certain
1418 /// situations when errors need to be logged before being discarded.
1425 /// let a = [1, 4, 2, 3];
1427 /// // this iterator sequence is complex.
1428 /// let sum = a.iter()
1430 /// .filter(|x| x % 2 == 0)
1431 /// .fold(0, |sum, i| sum + i);
1433 /// println!("{}", sum);
1435 /// // let's add some inspect() calls to investigate what's happening
1436 /// let sum = a.iter()
1438 /// .inspect(|x| println!("about to filter: {}", x))
1439 /// .filter(|x| x % 2 == 0)
1440 /// .inspect(|x| println!("made it through filter: {}", x))
1441 /// .fold(0, |sum, i| sum + i);
1443 /// println!("{}", sum);
1446 /// This will print:
1450 /// about to filter: 1
1451 /// about to filter: 4
1452 /// made it through filter: 4
1453 /// about to filter: 2
1454 /// made it through filter: 2
1455 /// about to filter: 3
1459 /// Logging errors before discarding them:
1462 /// let lines = ["1", "2", "a"];
1464 /// let sum: i32 = lines
1466 /// .map(|line| line.parse::<i32>())
1467 /// .inspect(|num| {
1468 /// if let Err(ref e) = *num {
1469 /// println!("Parsing error: {}", e);
1472 /// .filter_map(Result::ok)
1475 /// println!("Sum: {}", sum);
1478 /// This will print:
1481 /// Parsing error: invalid digit found in string
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1489 F: FnMut(&Self::Item),
1491 Inspect::new(self, f)
1494 /// Borrows an iterator, rather than consuming it.
1496 /// This is useful to allow applying iterator adaptors while still
1497 /// retaining ownership of the original iterator.
1504 /// let a = [1, 2, 3];
1506 /// let iter = a.iter();
1508 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1510 /// assert_eq!(sum, 6);
1512 /// // if we try to use iter again, it won't work. The following line
1513 /// // gives "error: use of moved value: `iter`
1514 /// // assert_eq!(iter.next(), None);
1516 /// // let's try that again
1517 /// let a = [1, 2, 3];
1519 /// let mut iter = a.iter();
1521 /// // instead, we add in a .by_ref()
1522 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1524 /// assert_eq!(sum, 3);
1526 /// // now this is just fine:
1527 /// assert_eq!(iter.next(), Some(&3));
1528 /// assert_eq!(iter.next(), None);
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 fn by_ref(&mut self) -> &mut Self
1538 /// Transforms an iterator into a collection.
1540 /// `collect()` can take anything iterable, and turn it into a relevant
1541 /// collection. This is one of the more powerful methods in the standard
1542 /// library, used in a variety of contexts.
1544 /// The most basic pattern in which `collect()` is used is to turn one
1545 /// collection into another. You take a collection, call [`iter`] on it,
1546 /// do a bunch of transformations, and then `collect()` at the end.
1548 /// `collect()` can also create instances of types that are not typical
1549 /// collections. For example, a [`String`] can be built from [`char`]s,
1550 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1551 /// into `Result<Collection<T>, E>`. See the examples below for more.
1553 /// Because `collect()` is so general, it can cause problems with type
1554 /// inference. As such, `collect()` is one of the few times you'll see
1555 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1556 /// helps the inference algorithm understand specifically which collection
1557 /// you're trying to collect into.
1564 /// let a = [1, 2, 3];
1566 /// let doubled: Vec<i32> = a.iter()
1567 /// .map(|&x| x * 2)
1570 /// assert_eq!(vec![2, 4, 6], doubled);
1573 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1574 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1576 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1579 /// use std::collections::VecDeque;
1581 /// let a = [1, 2, 3];
1583 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1585 /// assert_eq!(2, doubled[0]);
1586 /// assert_eq!(4, doubled[1]);
1587 /// assert_eq!(6, doubled[2]);
1590 /// Using the 'turbofish' instead of annotating `doubled`:
1593 /// let a = [1, 2, 3];
1595 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1597 /// assert_eq!(vec![2, 4, 6], doubled);
1600 /// Because `collect()` only cares about what you're collecting into, you can
1601 /// still use a partial type hint, `_`, with the turbofish:
1604 /// let a = [1, 2, 3];
1606 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1608 /// assert_eq!(vec![2, 4, 6], doubled);
1611 /// Using `collect()` to make a [`String`]:
1614 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1616 /// let hello: String = chars.iter()
1617 /// .map(|&x| x as u8)
1618 /// .map(|x| (x + 1) as char)
1621 /// assert_eq!("hello", hello);
1624 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1625 /// see if any of them failed:
1628 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1630 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1632 /// // gives us the first error
1633 /// assert_eq!(Err("nope"), result);
1635 /// let results = [Ok(1), Ok(3)];
1637 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1639 /// // gives us the list of answers
1640 /// assert_eq!(Ok(vec![1, 3]), result);
1643 /// [`iter`]: #tymethod.next
1644 /// [`String`]: ../../std/string/struct.String.html
1645 /// [`char`]: type@char
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1649 fn collect<B: FromIterator<Self::Item>>(self) -> B
1653 FromIterator::from_iter(self)
1656 /// Consumes an iterator, creating two collections from it.
1658 /// The predicate passed to `partition()` can return `true`, or `false`.
1659 /// `partition()` returns a pair, all of the elements for which it returned
1660 /// `true`, and all of the elements for which it returned `false`.
1662 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1664 /// [`is_partitioned()`]: #method.is_partitioned
1665 /// [`partition_in_place()`]: #method.partition_in_place
1672 /// let a = [1, 2, 3];
1674 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1676 /// .partition(|&n| n % 2 == 0);
1678 /// assert_eq!(even, vec![2]);
1679 /// assert_eq!(odd, vec![1, 3]);
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 fn partition<B, F>(self, f: F) -> (B, B)
1685 B: Default + Extend<Self::Item>,
1686 F: FnMut(&Self::Item) -> bool,
1689 fn extend<'a, T, B: Extend<T>>(
1690 mut f: impl FnMut(&T) -> bool + 'a,
1693 ) -> impl FnMut((), T) + 'a {
1698 right.extend_one(x);
1703 let mut left: B = Default::default();
1704 let mut right: B = Default::default();
1706 self.fold((), extend(f, &mut left, &mut right));
1711 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1712 /// such that all those that return `true` precede all those that return `false`.
1713 /// Returns the number of `true` elements found.
1715 /// The relative order of partitioned items is not maintained.
1717 /// See also [`is_partitioned()`] and [`partition()`].
1719 /// [`is_partitioned()`]: #method.is_partitioned
1720 /// [`partition()`]: #method.partition
1725 /// #![feature(iter_partition_in_place)]
1727 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1729 /// // Partition in-place between evens and odds
1730 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1732 /// assert_eq!(i, 3);
1733 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1734 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1736 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1737 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1739 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1740 P: FnMut(&T) -> bool,
1742 // FIXME: should we worry about the count overflowing? The only way to have more than
1743 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1745 // These closure "factory" functions exist to avoid genericity in `Self`.
1749 predicate: &'a mut impl FnMut(&T) -> bool,
1750 true_count: &'a mut usize,
1751 ) -> impl FnMut(&&mut T) -> bool + 'a {
1753 let p = predicate(&**x);
1754 *true_count += p as usize;
1760 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1761 move |x| predicate(&**x)
1764 // Repeatedly find the first `false` and swap it with the last `true`.
1765 let mut true_count = 0;
1766 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1767 if let Some(tail) = self.rfind(is_true(predicate)) {
1768 crate::mem::swap(head, tail);
1777 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1778 /// such that all those that return `true` precede all those that return `false`.
1780 /// See also [`partition()`] and [`partition_in_place()`].
1782 /// [`partition()`]: #method.partition
1783 /// [`partition_in_place()`]: #method.partition_in_place
1788 /// #![feature(iter_is_partitioned)]
1790 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1791 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1793 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1794 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1797 P: FnMut(Self::Item) -> bool,
1799 // Either all items test `true`, or the first clause stops at `false`
1800 // and we check that there are no more `true` items after that.
1801 self.all(&mut predicate) || !self.any(predicate)
1804 /// An iterator method that applies a function as long as it returns
1805 /// successfully, producing a single, final value.
1807 /// `try_fold()` takes two arguments: an initial value, and a closure with
1808 /// two arguments: an 'accumulator', and an element. The closure either
1809 /// returns successfully, with the value that the accumulator should have
1810 /// for the next iteration, or it returns failure, with an error value that
1811 /// is propagated back to the caller immediately (short-circuiting).
1813 /// The initial value is the value the accumulator will have on the first
1814 /// call. If applying the closure succeeded against every element of the
1815 /// iterator, `try_fold()` returns the final accumulator as success.
1817 /// Folding is useful whenever you have a collection of something, and want
1818 /// to produce a single value from it.
1820 /// # Note to Implementors
1822 /// Several of the other (forward) methods have default implementations in
1823 /// terms of this one, so try to implement this explicitly if it can
1824 /// do something better than the default `for` loop implementation.
1826 /// In particular, try to have this call `try_fold()` on the internal parts
1827 /// from which this iterator is composed. If multiple calls are needed,
1828 /// the `?` operator may be convenient for chaining the accumulator value
1829 /// along, but beware any invariants that need to be upheld before those
1830 /// early returns. This is a `&mut self` method, so iteration needs to be
1831 /// resumable after hitting an error here.
1838 /// let a = [1, 2, 3];
1840 /// // the checked sum of all of the elements of the array
1841 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1843 /// assert_eq!(sum, Some(6));
1846 /// Short-circuiting:
1849 /// let a = [10, 20, 30, 100, 40, 50];
1850 /// let mut it = a.iter();
1852 /// // This sum overflows when adding the 100 element
1853 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1854 /// assert_eq!(sum, None);
1856 /// // Because it short-circuited, the remaining elements are still
1857 /// // available through the iterator.
1858 /// assert_eq!(it.len(), 2);
1859 /// assert_eq!(it.next(), Some(&40));
1862 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1863 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1866 F: FnMut(B, Self::Item) -> R,
1869 let mut accum = init;
1870 while let Some(x) = self.next() {
1871 accum = f(accum, x)?;
1876 /// An iterator method that applies a fallible function to each item in the
1877 /// iterator, stopping at the first error and returning that error.
1879 /// This can also be thought of as the fallible form of [`for_each()`]
1880 /// or as the stateless version of [`try_fold()`].
1882 /// [`for_each()`]: #method.for_each
1883 /// [`try_fold()`]: #method.try_fold
1888 /// use std::fs::rename;
1889 /// use std::io::{stdout, Write};
1890 /// use std::path::Path;
1892 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1894 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1895 /// assert!(res.is_ok());
1897 /// let mut it = data.iter().cloned();
1898 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1899 /// assert!(res.is_err());
1900 /// // It short-circuited, so the remaining items are still in the iterator:
1901 /// assert_eq!(it.next(), Some("stale_bread.json"));
1904 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1905 fn try_for_each<F, R>(&mut self, f: F) -> R
1908 F: FnMut(Self::Item) -> R,
1912 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
1916 self.try_fold((), call(f))
1919 /// An iterator method that applies a function, producing a single, final value.
1921 /// `fold()` takes two arguments: an initial value, and a closure with two
1922 /// arguments: an 'accumulator', and an element. The closure returns the value that
1923 /// the accumulator should have for the next iteration.
1925 /// The initial value is the value the accumulator will have on the first
1928 /// After applying this closure to every element of the iterator, `fold()`
1929 /// returns the accumulator.
1931 /// This operation is sometimes called 'reduce' or 'inject'.
1933 /// Folding is useful whenever you have a collection of something, and want
1934 /// to produce a single value from it.
1936 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1937 /// may not terminate for infinite iterators, even on traits for which a
1938 /// result is determinable in finite time.
1940 /// # Note to Implementors
1942 /// Several of the other (forward) methods have default implementations in
1943 /// terms of this one, so try to implement this explicitly if it can
1944 /// do something better than the default `for` loop implementation.
1946 /// In particular, try to have this call `fold()` on the internal parts
1947 /// from which this iterator is composed.
1954 /// let a = [1, 2, 3];
1956 /// // the sum of all of the elements of the array
1957 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1959 /// assert_eq!(sum, 6);
1962 /// Let's walk through each step of the iteration here:
1964 /// | element | acc | x | result |
1965 /// |---------|-----|---|--------|
1967 /// | 1 | 0 | 1 | 1 |
1968 /// | 2 | 1 | 2 | 3 |
1969 /// | 3 | 3 | 3 | 6 |
1971 /// And so, our final result, `6`.
1973 /// It's common for people who haven't used iterators a lot to
1974 /// use a `for` loop with a list of things to build up a result. Those
1975 /// can be turned into `fold()`s:
1977 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1980 /// let numbers = [1, 2, 3, 4, 5];
1982 /// let mut result = 0;
1985 /// for i in &numbers {
1986 /// result = result + i;
1990 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1992 /// // they're the same
1993 /// assert_eq!(result, result2);
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2000 F: FnMut(B, Self::Item) -> B,
2002 let mut accum = init;
2003 while let Some(x) = self.next() {
2004 accum = f(accum, x);
2009 /// The same as [`fold()`](#method.fold), but uses the first element in the
2010 /// iterator as the initial value, folding every subsequent element into it.
2011 /// If the iterator is empty, return `None`; otherwise, return the result
2016 /// Find the maximum value:
2019 /// #![feature(iterator_fold_self)]
2021 /// fn find_max<I>(iter: I) -> Option<I::Item>
2022 /// where I: Iterator,
2025 /// iter.fold_first(|a, b| {
2026 /// if a >= b { a } else { b }
2029 /// let a = [10, 20, 5, -23, 0];
2030 /// let b: [u32; 0] = [];
2032 /// assert_eq!(find_max(a.iter()), Some(&20));
2033 /// assert_eq!(find_max(b.iter()), None);
2036 #[unstable(feature = "iterator_fold_self", issue = "68125")]
2037 fn fold_first<F>(mut self, f: F) -> Option<Self::Item>
2040 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2042 let first = self.next()?;
2043 Some(self.fold(first, f))
2046 /// Tests if every element of the iterator matches a predicate.
2048 /// `all()` takes a closure that returns `true` or `false`. It applies
2049 /// this closure to each element of the iterator, and if they all return
2050 /// `true`, then so does `all()`. If any of them return `false`, it
2051 /// returns `false`.
2053 /// `all()` is short-circuiting; in other words, it will stop processing
2054 /// as soon as it finds a `false`, given that no matter what else happens,
2055 /// the result will also be `false`.
2057 /// An empty iterator returns `true`.
2064 /// let a = [1, 2, 3];
2066 /// assert!(a.iter().all(|&x| x > 0));
2068 /// assert!(!a.iter().all(|&x| x > 2));
2071 /// Stopping at the first `false`:
2074 /// let a = [1, 2, 3];
2076 /// let mut iter = a.iter();
2078 /// assert!(!iter.all(|&x| x != 2));
2080 /// // we can still use `iter`, as there are more elements.
2081 /// assert_eq!(iter.next(), Some(&3));
2084 #[stable(feature = "rust1", since = "1.0.0")]
2085 fn all<F>(&mut self, f: F) -> bool
2088 F: FnMut(Self::Item) -> bool,
2091 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2093 if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) }
2096 self.try_fold((), check(f)) == LoopState::Continue(())
2099 /// Tests if any element of the iterator matches a predicate.
2101 /// `any()` takes a closure that returns `true` or `false`. It applies
2102 /// this closure to each element of the iterator, and if any of them return
2103 /// `true`, then so does `any()`. If they all return `false`, it
2104 /// returns `false`.
2106 /// `any()` is short-circuiting; in other words, it will stop processing
2107 /// as soon as it finds a `true`, given that no matter what else happens,
2108 /// the result will also be `true`.
2110 /// An empty iterator returns `false`.
2117 /// let a = [1, 2, 3];
2119 /// assert!(a.iter().any(|&x| x > 0));
2121 /// assert!(!a.iter().any(|&x| x > 5));
2124 /// Stopping at the first `true`:
2127 /// let a = [1, 2, 3];
2129 /// let mut iter = a.iter();
2131 /// assert!(iter.any(|&x| x != 2));
2133 /// // we can still use `iter`, as there are more elements.
2134 /// assert_eq!(iter.next(), Some(&2));
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 fn any<F>(&mut self, f: F) -> bool
2141 F: FnMut(Self::Item) -> bool,
2144 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2146 if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) }
2150 self.try_fold((), check(f)) == LoopState::Break(())
2153 /// Searches for an element of an iterator that satisfies a predicate.
2155 /// `find()` takes a closure that returns `true` or `false`. It applies
2156 /// this closure to each element of the iterator, and if any of them return
2157 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2158 /// `false`, it returns [`None`].
2160 /// `find()` is short-circuiting; in other words, it will stop processing
2161 /// as soon as the closure returns `true`.
2163 /// Because `find()` takes a reference, and many iterators iterate over
2164 /// references, this leads to a possibly confusing situation where the
2165 /// argument is a double reference. You can see this effect in the
2166 /// examples below, with `&&x`.
2168 /// [`Some(element)`]: Some
2175 /// let a = [1, 2, 3];
2177 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2179 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2182 /// Stopping at the first `true`:
2185 /// let a = [1, 2, 3];
2187 /// let mut iter = a.iter();
2189 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2191 /// // we can still use `iter`, as there are more elements.
2192 /// assert_eq!(iter.next(), Some(&3));
2195 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2201 P: FnMut(&Self::Item) -> bool,
2205 mut predicate: impl FnMut(&T) -> bool,
2206 ) -> impl FnMut((), T) -> LoopState<(), T> {
2208 if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) }
2212 self.try_fold((), check(predicate)).break_value()
2215 /// Applies function to the elements of iterator and returns
2216 /// the first non-none result.
2218 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2224 /// let a = ["lol", "NaN", "2", "5"];
2226 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2228 /// assert_eq!(first_number, Some(2));
2231 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2232 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2235 F: FnMut(Self::Item) -> Option<B>,
2238 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> LoopState<(), B> {
2239 move |(), x| match f(x) {
2240 Some(x) => LoopState::Break(x),
2241 None => LoopState::Continue(()),
2245 self.try_fold((), check(f)).break_value()
2248 /// Applies function to the elements of iterator and returns
2249 /// the first true result or the first error.
2254 /// #![feature(try_find)]
2256 /// let a = ["1", "2", "lol", "NaN", "5"];
2258 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2259 /// Ok(s.parse::<i32>()? == search)
2262 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2263 /// assert_eq!(result, Ok(Some(&"2")));
2265 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2266 /// assert!(result.is_err());
2269 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2270 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2273 F: FnMut(&Self::Item) -> R,
2277 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> LoopState<(), Result<T, R::Error>>
2282 move |(), x| match f(&x).into_result() {
2283 Ok(false) => LoopState::Continue(()),
2284 Ok(true) => LoopState::Break(Ok(x)),
2285 Err(x) => LoopState::Break(Err(x)),
2289 self.try_fold((), check(f)).break_value().transpose()
2292 /// Searches for an element in an iterator, returning its index.
2294 /// `position()` takes a closure that returns `true` or `false`. It applies
2295 /// this closure to each element of the iterator, and if one of them
2296 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2297 /// them return `false`, it returns [`None`].
2299 /// `position()` is short-circuiting; in other words, it will stop
2300 /// processing as soon as it finds a `true`.
2302 /// # Overflow Behavior
2304 /// The method does no guarding against overflows, so if there are more
2305 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2306 /// result or panics. If debug assertions are enabled, a panic is
2311 /// This function might panic if the iterator has more than `usize::MAX`
2312 /// non-matching elements.
2314 /// [`Some(index)`]: Some
2315 /// [`usize::MAX`]: crate::usize::MAX
2322 /// let a = [1, 2, 3];
2324 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2326 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2329 /// Stopping at the first `true`:
2332 /// let a = [1, 2, 3, 4];
2334 /// let mut iter = a.iter();
2336 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2338 /// // we can still use `iter`, as there are more elements.
2339 /// assert_eq!(iter.next(), Some(&3));
2341 /// // The returned index depends on iterator state
2342 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2346 #[stable(feature = "rust1", since = "1.0.0")]
2347 fn position<P>(&mut self, predicate: P) -> Option<usize>
2350 P: FnMut(Self::Item) -> bool,
2354 mut predicate: impl FnMut(T) -> bool,
2355 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2356 // The addition might panic on overflow
2358 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) }
2362 self.try_fold(0, check(predicate)).break_value()
2365 /// Searches for an element in an iterator from the right, returning its
2368 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2369 /// this closure to each element of the iterator, starting from the end,
2370 /// and if one of them returns `true`, then `rposition()` returns
2371 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2373 /// `rposition()` is short-circuiting; in other words, it will stop
2374 /// processing as soon as it finds a `true`.
2376 /// [`Some(index)`]: Some
2383 /// let a = [1, 2, 3];
2385 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2387 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2390 /// Stopping at the first `true`:
2393 /// let a = [1, 2, 3];
2395 /// let mut iter = a.iter();
2397 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2399 /// // we can still use `iter`, as there are more elements.
2400 /// assert_eq!(iter.next(), Some(&1));
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2406 P: FnMut(Self::Item) -> bool,
2407 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2409 // No need for an overflow check here, because `ExactSizeIterator`
2410 // implies that the number of elements fits into a `usize`.
2413 mut predicate: impl FnMut(T) -> bool,
2414 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2417 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) }
2422 self.try_rfold(n, check(predicate)).break_value()
2425 /// Returns the maximum element of an iterator.
2427 /// If several elements are equally maximum, the last element is
2428 /// returned. If the iterator is empty, [`None`] is returned.
2435 /// let a = [1, 2, 3];
2436 /// let b: Vec<u32> = Vec::new();
2438 /// assert_eq!(a.iter().max(), Some(&3));
2439 /// assert_eq!(b.iter().max(), None);
2442 #[stable(feature = "rust1", since = "1.0.0")]
2443 fn max(self) -> Option<Self::Item>
2448 self.max_by(Ord::cmp)
2451 /// Returns the minimum element of an iterator.
2453 /// If several elements are equally minimum, the first element is
2454 /// returned. If the iterator is empty, [`None`] is returned.
2461 /// let a = [1, 2, 3];
2462 /// let b: Vec<u32> = Vec::new();
2464 /// assert_eq!(a.iter().min(), Some(&1));
2465 /// assert_eq!(b.iter().min(), None);
2468 #[stable(feature = "rust1", since = "1.0.0")]
2469 fn min(self) -> Option<Self::Item>
2474 self.min_by(Ord::cmp)
2477 /// Returns the element that gives the maximum value from the
2478 /// specified function.
2480 /// If several elements are equally maximum, the last element is
2481 /// returned. If the iterator is empty, [`None`] is returned.
2486 /// let a = [-3_i32, 0, 1, 5, -10];
2487 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2490 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2491 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2494 F: FnMut(&Self::Item) -> B,
2497 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2502 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2506 let (_, x) = self.map(key(f)).max_by(compare)?;
2510 /// Returns the element that gives the maximum value with respect to the
2511 /// specified comparison function.
2513 /// If several elements are equally maximum, the last element is
2514 /// returned. If the iterator is empty, [`None`] is returned.
2519 /// let a = [-3_i32, 0, 1, 5, -10];
2520 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2523 #[stable(feature = "iter_max_by", since = "1.15.0")]
2524 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2527 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2530 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2531 move |x, y| cmp::max_by(x, y, &mut compare)
2534 self.fold_first(fold(compare))
2537 /// Returns the element that gives the minimum value from the
2538 /// specified function.
2540 /// If several elements are equally minimum, the first element is
2541 /// returned. If the iterator is empty, [`None`] is returned.
2546 /// let a = [-3_i32, 0, 1, 5, -10];
2547 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2550 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2551 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2554 F: FnMut(&Self::Item) -> B,
2557 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2562 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2566 let (_, x) = self.map(key(f)).min_by(compare)?;
2570 /// Returns the element that gives the minimum value with respect to the
2571 /// specified comparison function.
2573 /// If several elements are equally minimum, the first element is
2574 /// returned. If the iterator is empty, [`None`] is returned.
2579 /// let a = [-3_i32, 0, 1, 5, -10];
2580 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2583 #[stable(feature = "iter_min_by", since = "1.15.0")]
2584 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2587 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2590 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2591 move |x, y| cmp::min_by(x, y, &mut compare)
2594 self.fold_first(fold(compare))
2597 /// Reverses an iterator's direction.
2599 /// Usually, iterators iterate from left to right. After using `rev()`,
2600 /// an iterator will instead iterate from right to left.
2602 /// This is only possible if the iterator has an end, so `rev()` only
2603 /// works on [`DoubleEndedIterator`]s.
2605 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2610 /// let a = [1, 2, 3];
2612 /// let mut iter = a.iter().rev();
2614 /// assert_eq!(iter.next(), Some(&3));
2615 /// assert_eq!(iter.next(), Some(&2));
2616 /// assert_eq!(iter.next(), Some(&1));
2618 /// assert_eq!(iter.next(), None);
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 fn rev(self) -> Rev<Self>
2624 Self: Sized + DoubleEndedIterator,
2629 /// Converts an iterator of pairs into a pair of containers.
2631 /// `unzip()` consumes an entire iterator of pairs, producing two
2632 /// collections: one from the left elements of the pairs, and one
2633 /// from the right elements.
2635 /// This function is, in some sense, the opposite of [`zip`].
2637 /// [`zip`]: #method.zip
2644 /// let a = [(1, 2), (3, 4)];
2646 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2648 /// assert_eq!(left, [1, 3]);
2649 /// assert_eq!(right, [2, 4]);
2651 #[stable(feature = "rust1", since = "1.0.0")]
2652 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2654 FromA: Default + Extend<A>,
2655 FromB: Default + Extend<B>,
2656 Self: Sized + Iterator<Item = (A, B)>,
2658 fn extend<'a, A, B>(
2659 ts: &'a mut impl Extend<A>,
2660 us: &'a mut impl Extend<B>,
2661 ) -> impl FnMut((), (A, B)) + 'a {
2668 let mut ts: FromA = Default::default();
2669 let mut us: FromB = Default::default();
2671 let (lower_bound, _) = self.size_hint();
2672 if lower_bound > 0 {
2673 ts.extend_reserve(lower_bound);
2674 us.extend_reserve(lower_bound);
2677 self.fold((), extend(&mut ts, &mut us));
2682 /// Creates an iterator which copies all of its elements.
2684 /// This is useful when you have an iterator over `&T`, but you need an
2685 /// iterator over `T`.
2692 /// let a = [1, 2, 3];
2694 /// let v_copied: Vec<_> = a.iter().copied().collect();
2696 /// // copied is the same as .map(|&x| x)
2697 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2699 /// assert_eq!(v_copied, vec![1, 2, 3]);
2700 /// assert_eq!(v_map, vec![1, 2, 3]);
2702 #[stable(feature = "iter_copied", since = "1.36.0")]
2703 fn copied<'a, T: 'a>(self) -> Copied<Self>
2705 Self: Sized + Iterator<Item = &'a T>,
2711 /// Creates an iterator which [`clone`]s all of its elements.
2713 /// This is useful when you have an iterator over `&T`, but you need an
2714 /// iterator over `T`.
2716 /// [`clone`]: crate::clone::Clone::clone
2723 /// let a = [1, 2, 3];
2725 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2727 /// // cloned is the same as .map(|&x| x), for integers
2728 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2730 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2731 /// assert_eq!(v_map, vec![1, 2, 3]);
2733 #[stable(feature = "rust1", since = "1.0.0")]
2734 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2736 Self: Sized + Iterator<Item = &'a T>,
2742 /// Repeats an iterator endlessly.
2744 /// Instead of stopping at [`None`], the iterator will instead start again,
2745 /// from the beginning. After iterating again, it will start at the
2746 /// beginning again. And again. And again. Forever.
2753 /// let a = [1, 2, 3];
2755 /// let mut it = a.iter().cycle();
2757 /// assert_eq!(it.next(), Some(&1));
2758 /// assert_eq!(it.next(), Some(&2));
2759 /// assert_eq!(it.next(), Some(&3));
2760 /// assert_eq!(it.next(), Some(&1));
2761 /// assert_eq!(it.next(), Some(&2));
2762 /// assert_eq!(it.next(), Some(&3));
2763 /// assert_eq!(it.next(), Some(&1));
2765 #[stable(feature = "rust1", since = "1.0.0")]
2767 fn cycle(self) -> Cycle<Self>
2769 Self: Sized + Clone,
2774 /// Sums the elements of an iterator.
2776 /// Takes each element, adds them together, and returns the result.
2778 /// An empty iterator returns the zero value of the type.
2782 /// When calling `sum()` and a primitive integer type is being returned, this
2783 /// method will panic if the computation overflows and debug assertions are
2791 /// let a = [1, 2, 3];
2792 /// let sum: i32 = a.iter().sum();
2794 /// assert_eq!(sum, 6);
2796 #[stable(feature = "iter_arith", since = "1.11.0")]
2797 fn sum<S>(self) -> S
2805 /// Iterates over the entire iterator, multiplying all the elements
2807 /// An empty iterator returns the one value of the type.
2811 /// When calling `product()` and a primitive integer type is being returned,
2812 /// method will panic if the computation overflows and debug assertions are
2818 /// fn factorial(n: u32) -> u32 {
2819 /// (1..=n).product()
2821 /// assert_eq!(factorial(0), 1);
2822 /// assert_eq!(factorial(1), 1);
2823 /// assert_eq!(factorial(5), 120);
2825 #[stable(feature = "iter_arith", since = "1.11.0")]
2826 fn product<P>(self) -> P
2829 P: Product<Self::Item>,
2831 Product::product(self)
2834 /// Lexicographically compares the elements of this `Iterator` with those
2840 /// use std::cmp::Ordering;
2842 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2843 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2844 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2846 #[stable(feature = "iter_order", since = "1.5.0")]
2847 fn cmp<I>(self, other: I) -> Ordering
2849 I: IntoIterator<Item = Self::Item>,
2853 self.cmp_by(other, |x, y| x.cmp(&y))
2856 /// Lexicographically compares the elements of this `Iterator` with those
2857 /// of another with respect to the specified comparison function.
2864 /// #![feature(iter_order_by)]
2866 /// use std::cmp::Ordering;
2868 /// let xs = [1, 2, 3, 4];
2869 /// let ys = [1, 4, 9, 16];
2871 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2872 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2873 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2875 #[unstable(feature = "iter_order_by", issue = "64295")]
2876 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
2880 F: FnMut(Self::Item, I::Item) -> Ordering,
2882 let mut other = other.into_iter();
2885 let x = match self.next() {
2887 if other.next().is_none() {
2888 return Ordering::Equal;
2890 return Ordering::Less;
2896 let y = match other.next() {
2897 None => return Ordering::Greater,
2902 Ordering::Equal => (),
2903 non_eq => return non_eq,
2908 /// Lexicographically compares the elements of this `Iterator` with those
2914 /// use std::cmp::Ordering;
2916 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2917 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2918 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2920 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2922 #[stable(feature = "iter_order", since = "1.5.0")]
2923 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
2926 Self::Item: PartialOrd<I::Item>,
2929 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
2932 /// Lexicographically compares the elements of this `Iterator` with those
2933 /// of another with respect to the specified comparison function.
2940 /// #![feature(iter_order_by)]
2942 /// use std::cmp::Ordering;
2944 /// let xs = [1.0, 2.0, 3.0, 4.0];
2945 /// let ys = [1.0, 4.0, 9.0, 16.0];
2948 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2949 /// Some(Ordering::Less)
2952 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2953 /// Some(Ordering::Equal)
2956 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2957 /// Some(Ordering::Greater)
2960 #[unstable(feature = "iter_order_by", issue = "64295")]
2961 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
2965 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
2967 let mut other = other.into_iter();
2970 let x = match self.next() {
2972 if other.next().is_none() {
2973 return Some(Ordering::Equal);
2975 return Some(Ordering::Less);
2981 let y = match other.next() {
2982 None => return Some(Ordering::Greater),
2986 match partial_cmp(x, y) {
2987 Some(Ordering::Equal) => (),
2988 non_eq => return non_eq,
2993 /// Determines if the elements of this `Iterator` are equal to those of
2999 /// assert_eq!([1].iter().eq([1].iter()), true);
3000 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3002 #[stable(feature = "iter_order", since = "1.5.0")]
3003 fn eq<I>(self, other: I) -> bool
3006 Self::Item: PartialEq<I::Item>,
3009 self.eq_by(other, |x, y| x == y)
3012 /// Determines if the elements of this `Iterator` are equal to those of
3013 /// another with respect to the specified equality function.
3020 /// #![feature(iter_order_by)]
3022 /// let xs = [1, 2, 3, 4];
3023 /// let ys = [1, 4, 9, 16];
3025 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3027 #[unstable(feature = "iter_order_by", issue = "64295")]
3028 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3032 F: FnMut(Self::Item, I::Item) -> bool,
3034 let mut other = other.into_iter();
3037 let x = match self.next() {
3038 None => return other.next().is_none(),
3042 let y = match other.next() {
3043 None => return false,
3053 /// Determines if the elements of this `Iterator` are unequal to those of
3059 /// assert_eq!([1].iter().ne([1].iter()), false);
3060 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3062 #[stable(feature = "iter_order", since = "1.5.0")]
3063 fn ne<I>(self, other: I) -> bool
3066 Self::Item: PartialEq<I::Item>,
3072 /// Determines if the elements of this `Iterator` are lexicographically
3073 /// less than those of another.
3078 /// assert_eq!([1].iter().lt([1].iter()), false);
3079 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3080 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3081 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3083 #[stable(feature = "iter_order", since = "1.5.0")]
3084 fn lt<I>(self, other: I) -> bool
3087 Self::Item: PartialOrd<I::Item>,
3090 self.partial_cmp(other) == Some(Ordering::Less)
3093 /// Determines if the elements of this `Iterator` are lexicographically
3094 /// less or equal to those of another.
3099 /// assert_eq!([1].iter().le([1].iter()), true);
3100 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3101 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3102 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3104 #[stable(feature = "iter_order", since = "1.5.0")]
3105 fn le<I>(self, other: I) -> bool
3108 Self::Item: PartialOrd<I::Item>,
3111 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3114 /// Determines if the elements of this `Iterator` are lexicographically
3115 /// greater than those of another.
3120 /// assert_eq!([1].iter().gt([1].iter()), false);
3121 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3122 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3123 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3125 #[stable(feature = "iter_order", since = "1.5.0")]
3126 fn gt<I>(self, other: I) -> bool
3129 Self::Item: PartialOrd<I::Item>,
3132 self.partial_cmp(other) == Some(Ordering::Greater)
3135 /// Determines if the elements of this `Iterator` are lexicographically
3136 /// greater than or equal to those of another.
3141 /// assert_eq!([1].iter().ge([1].iter()), true);
3142 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3143 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3144 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3146 #[stable(feature = "iter_order", since = "1.5.0")]
3147 fn ge<I>(self, other: I) -> bool
3150 Self::Item: PartialOrd<I::Item>,
3153 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3156 /// Checks if the elements of this iterator are sorted.
3158 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3159 /// iterator yields exactly zero or one element, `true` is returned.
3161 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3162 /// implies that this function returns `false` if any two consecutive items are not
3168 /// #![feature(is_sorted)]
3170 /// assert!([1, 2, 2, 9].iter().is_sorted());
3171 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3172 /// assert!([0].iter().is_sorted());
3173 /// assert!(std::iter::empty::<i32>().is_sorted());
3174 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3177 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3178 fn is_sorted(self) -> bool
3181 Self::Item: PartialOrd,
3183 self.is_sorted_by(PartialOrd::partial_cmp)
3186 /// Checks if the elements of this iterator are sorted using the given comparator function.
3188 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3189 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3190 /// [`is_sorted`]; see its documentation for more information.
3195 /// #![feature(is_sorted)]
3197 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3198 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3199 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3200 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3201 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3204 /// [`is_sorted`]: #method.is_sorted
3205 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3206 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3209 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3211 let mut last = match self.next() {
3213 None => return true,
3216 while let Some(curr) = self.next() {
3217 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3226 /// Checks if the elements of this iterator are sorted using the given key extraction
3229 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3230 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3231 /// its documentation for more information.
3233 /// [`is_sorted`]: #method.is_sorted
3238 /// #![feature(is_sorted)]
3240 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3241 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3244 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3245 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3248 F: FnMut(Self::Item) -> K,
3251 self.map(f).is_sorted()
3254 /// See [TrustedRandomAccess]
3257 #[unstable(feature = "trusted_random_access", issue = "none")]
3258 unsafe fn get_unchecked(&mut self, _idx: usize) -> Self::Item
3260 Self: TrustedRandomAccess,
3262 unreachable!("Always specialized");
3266 #[stable(feature = "rust1", since = "1.0.0")]
3267 impl<I: Iterator + ?Sized> Iterator for &mut I {
3268 type Item = I::Item;
3269 fn next(&mut self) -> Option<I::Item> {
3272 fn size_hint(&self) -> (usize, Option<usize>) {
3273 (**self).size_hint()
3275 fn nth(&mut self, n: usize) -> Option<Self::Item> {