2 use crate::cmp::{self, Ordering};
3 use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
5 use super::super::try_process;
6 use super::super::ByRefSized;
7 use super::super::TrustedRandomAccessNoCoerce;
8 use super::super::{ArrayChunks, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
9 use super::super::{FlatMap, Flatten};
10 use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip};
12 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
15 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
17 /// A trait for dealing with iterators.
19 /// This is the main iterator trait. For more about the concept of iterators
20 /// generally, please see the [module-level documentation]. In particular, you
21 /// may want to know how to [implement `Iterator`][impl].
23 /// [module-level documentation]: crate::iter
24 /// [impl]: crate::iter#implementing-iterator
25 #[stable(feature = "rust1", since = "1.0.0")]
26 #[rustc_on_unimplemented(
28 _Self = "std::ops::RangeTo<Idx>",
29 label = "if you meant to iterate until a value, add a starting value",
30 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
31 bounded `Range`: `0..end`"
34 _Self = "std::ops::RangeToInclusive<Idx>",
35 label = "if you meant to iterate until a value (including it), add a starting value",
36 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
37 to have a bounded `RangeInclusive`: `0..=end`"
41 label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
43 on(_Self = "&[]", label = "`{Self}` is not an iterator; try calling `.iter()`"),
45 _Self = "std::vec::Vec<T, A>",
46 label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
50 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
53 _Self = "std::string::String",
54 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
58 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
59 syntax `start..end` or the inclusive range syntax `start..=end`"
61 label = "`{Self}` is not an iterator",
62 message = "`{Self}` is not an iterator"
65 #[rustc_diagnostic_item = "Iterator"]
66 #[must_use = "iterators are lazy and do nothing unless consumed"]
68 /// The type of the elements being iterated over.
69 #[rustc_diagnostic_item = "IteratorItem"]
70 #[stable(feature = "rust1", since = "1.0.0")]
73 /// Advances the iterator and returns the next value.
75 /// Returns [`None`] when iteration is finished. Individual iterator
76 /// implementations may choose to resume iteration, and so calling `next()`
77 /// again may or may not eventually start returning [`Some(Item)`] again at some
80 /// [`Some(Item)`]: Some
87 /// let a = [1, 2, 3];
89 /// let mut iter = a.iter();
91 /// // A call to next() returns the next value...
92 /// assert_eq!(Some(&1), iter.next());
93 /// assert_eq!(Some(&2), iter.next());
94 /// assert_eq!(Some(&3), iter.next());
96 /// // ... and then None once it's over.
97 /// assert_eq!(None, iter.next());
99 /// // More calls may or may not return `None`. Here, they always will.
100 /// assert_eq!(None, iter.next());
101 /// assert_eq!(None, iter.next());
104 #[stable(feature = "rust1", since = "1.0.0")]
105 fn next(&mut self) -> Option<Self::Item>;
107 /// Advances the iterator and returns an array containing the next `N` values.
109 /// If there are not enough elements to fill the array then `Err` is returned
110 /// containing an iterator over the remaining elements.
117 /// #![feature(iter_next_chunk)]
119 /// let mut iter = "lorem".chars();
121 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
122 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
123 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
126 /// Split a string and get the first three items.
129 /// #![feature(iter_next_chunk)]
131 /// let quote = "not all those who wander are lost";
132 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
133 /// assert_eq!(first, "not");
134 /// assert_eq!(second, "all");
135 /// assert_eq!(third, "those");
138 #[unstable(feature = "iter_next_chunk", reason = "recently added", issue = "98326")]
139 fn next_chunk<const N: usize>(
141 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
145 array::iter_next_chunk(self)
148 /// Returns the bounds on the remaining length of the iterator.
150 /// Specifically, `size_hint()` returns a tuple where the first element
151 /// is the lower bound, and the second element is the upper bound.
153 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
154 /// A [`None`] here means that either there is no known upper bound, or the
155 /// upper bound is larger than [`usize`].
157 /// # Implementation notes
159 /// It is not enforced that an iterator implementation yields the declared
160 /// number of elements. A buggy iterator may yield less than the lower bound
161 /// or more than the upper bound of elements.
163 /// `size_hint()` is primarily intended to be used for optimizations such as
164 /// reserving space for the elements of the iterator, but must not be
165 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
166 /// implementation of `size_hint()` should not lead to memory safety
169 /// That said, the implementation should provide a correct estimation,
170 /// because otherwise it would be a violation of the trait's protocol.
172 /// The default implementation returns <code>(0, [None])</code> which is correct for any
180 /// let a = [1, 2, 3];
181 /// let mut iter = a.iter();
183 /// assert_eq!((3, Some(3)), iter.size_hint());
184 /// let _ = iter.next();
185 /// assert_eq!((2, Some(2)), iter.size_hint());
188 /// A more complex example:
191 /// // The even numbers in the range of zero to nine.
192 /// let iter = (0..10).filter(|x| x % 2 == 0);
194 /// // We might iterate from zero to ten times. Knowing that it's five
195 /// // exactly wouldn't be possible without executing filter().
196 /// assert_eq!((0, Some(10)), iter.size_hint());
198 /// // Let's add five more numbers with chain()
199 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
201 /// // now both bounds are increased by five
202 /// assert_eq!((5, Some(15)), iter.size_hint());
205 /// Returning `None` for an upper bound:
208 /// // an infinite iterator has no upper bound
209 /// // and the maximum possible lower bound
212 /// assert_eq!((usize::MAX, None), iter.size_hint());
215 #[stable(feature = "rust1", since = "1.0.0")]
216 fn size_hint(&self) -> (usize, Option<usize>) {
220 /// Consumes the iterator, counting the number of iterations and returning it.
222 /// This method will call [`next`] repeatedly until [`None`] is encountered,
223 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
224 /// called at least once even if the iterator does not have any elements.
226 /// [`next`]: Iterator::next
228 /// # Overflow Behavior
230 /// The method does no guarding against overflows, so counting elements of
231 /// an iterator with more than [`usize::MAX`] elements either produces the
232 /// wrong result or panics. If debug assertions are enabled, a panic is
237 /// This function might panic if the iterator has more than [`usize::MAX`]
245 /// let a = [1, 2, 3];
246 /// assert_eq!(a.iter().count(), 3);
248 /// let a = [1, 2, 3, 4, 5];
249 /// assert_eq!(a.iter().count(), 5);
252 #[stable(feature = "rust1", since = "1.0.0")]
253 fn count(self) -> usize
259 #[rustc_inherit_overflow_checks]
260 |count, _| count + 1,
264 /// Consumes the iterator, returning the last element.
266 /// This method will evaluate the iterator until it returns [`None`]. While
267 /// doing so, it keeps track of the current element. After [`None`] is
268 /// returned, `last()` will then return the last element it saw.
275 /// let a = [1, 2, 3];
276 /// assert_eq!(a.iter().last(), Some(&3));
278 /// let a = [1, 2, 3, 4, 5];
279 /// assert_eq!(a.iter().last(), Some(&5));
282 #[stable(feature = "rust1", since = "1.0.0")]
283 fn last(self) -> Option<Self::Item>
288 fn some<T>(_: Option<T>, x: T) -> Option<T> {
292 self.fold(None, some)
295 /// Advances the iterator by `n` elements.
297 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
298 /// times until [`None`] is encountered.
300 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
301 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
302 /// of elements the iterator is advanced by before running out of elements (i.e. the
303 /// length of the iterator). Note that `k` is always less than `n`.
305 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
306 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
307 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
309 /// [`Flatten`]: crate::iter::Flatten
310 /// [`next`]: Iterator::next
317 /// #![feature(iter_advance_by)]
319 /// let a = [1, 2, 3, 4];
320 /// let mut iter = a.iter();
322 /// assert_eq!(iter.advance_by(2), Ok(()));
323 /// assert_eq!(iter.next(), Some(&3));
324 /// assert_eq!(iter.advance_by(0), Ok(()));
325 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
328 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
329 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
331 self.next().ok_or(i)?;
336 /// Returns the `n`th element of the iterator.
338 /// Like most indexing operations, the count starts from zero, so `nth(0)`
339 /// returns the first value, `nth(1)` the second, and so on.
341 /// Note that all preceding elements, as well as the returned element, will be
342 /// consumed from the iterator. That means that the preceding elements will be
343 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
344 /// will return different elements.
346 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
354 /// let a = [1, 2, 3];
355 /// assert_eq!(a.iter().nth(1), Some(&2));
358 /// Calling `nth()` multiple times doesn't rewind the iterator:
361 /// let a = [1, 2, 3];
363 /// let mut iter = a.iter();
365 /// assert_eq!(iter.nth(1), Some(&2));
366 /// assert_eq!(iter.nth(1), None);
369 /// Returning `None` if there are less than `n + 1` elements:
372 /// let a = [1, 2, 3];
373 /// assert_eq!(a.iter().nth(10), None);
376 #[stable(feature = "rust1", since = "1.0.0")]
377 fn nth(&mut self, n: usize) -> Option<Self::Item> {
378 self.advance_by(n).ok()?;
382 /// Creates an iterator starting at the same point, but stepping by
383 /// the given amount at each iteration.
385 /// Note 1: The first element of the iterator will always be returned,
386 /// regardless of the step given.
388 /// Note 2: The time at which ignored elements are pulled is not fixed.
389 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
390 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
391 /// `advance_n_and_return_first(&mut self, step)`,
392 /// `advance_n_and_return_first(&mut self, step)`, …
393 /// Which way is used may change for some iterators for performance reasons.
394 /// The second way will advance the iterator earlier and may consume more items.
396 /// `advance_n_and_return_first` is the equivalent of:
398 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
402 /// let next = iter.next();
412 /// The method will panic if the given step is `0`.
419 /// let a = [0, 1, 2, 3, 4, 5];
420 /// let mut iter = a.iter().step_by(2);
422 /// assert_eq!(iter.next(), Some(&0));
423 /// assert_eq!(iter.next(), Some(&2));
424 /// assert_eq!(iter.next(), Some(&4));
425 /// assert_eq!(iter.next(), None);
428 #[stable(feature = "iterator_step_by", since = "1.28.0")]
429 fn step_by(self, step: usize) -> StepBy<Self>
433 StepBy::new(self, step)
436 /// Takes two iterators and creates a new iterator over both in sequence.
438 /// `chain()` will return a new iterator which will first iterate over
439 /// values from the first iterator and then over values from the second
442 /// In other words, it links two iterators together, in a chain. 🔗
444 /// [`once`] is commonly used to adapt a single value into a chain of
445 /// other kinds of iteration.
452 /// let a1 = [1, 2, 3];
453 /// let a2 = [4, 5, 6];
455 /// let mut iter = a1.iter().chain(a2.iter());
457 /// assert_eq!(iter.next(), Some(&1));
458 /// assert_eq!(iter.next(), Some(&2));
459 /// assert_eq!(iter.next(), Some(&3));
460 /// assert_eq!(iter.next(), Some(&4));
461 /// assert_eq!(iter.next(), Some(&5));
462 /// assert_eq!(iter.next(), Some(&6));
463 /// assert_eq!(iter.next(), None);
466 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
467 /// anything that can be converted into an [`Iterator`], not just an
468 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
469 /// [`IntoIterator`], and so can be passed to `chain()` directly:
472 /// let s1 = &[1, 2, 3];
473 /// let s2 = &[4, 5, 6];
475 /// let mut iter = s1.iter().chain(s2);
477 /// assert_eq!(iter.next(), Some(&1));
478 /// assert_eq!(iter.next(), Some(&2));
479 /// assert_eq!(iter.next(), Some(&3));
480 /// assert_eq!(iter.next(), Some(&4));
481 /// assert_eq!(iter.next(), Some(&5));
482 /// assert_eq!(iter.next(), Some(&6));
483 /// assert_eq!(iter.next(), None);
486 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
490 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
491 /// use std::os::windows::ffi::OsStrExt;
492 /// s.encode_wide().chain(std::iter::once(0)).collect()
496 /// [`once`]: crate::iter::once
497 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
499 #[stable(feature = "rust1", since = "1.0.0")]
500 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
503 U: IntoIterator<Item = Self::Item>,
505 Chain::new(self, other.into_iter())
508 /// 'Zips up' two iterators into a single iterator of pairs.
510 /// `zip()` returns a new iterator that will iterate over two other
511 /// iterators, returning a tuple where the first element comes from the
512 /// first iterator, and the second element comes from the second iterator.
514 /// In other words, it zips two iterators together, into a single one.
516 /// If either iterator returns [`None`], [`next`] from the zipped iterator
517 /// will return [`None`].
518 /// If the zipped iterator has no more elements to return then each further attempt to advance
519 /// it will first try to advance the first iterator at most one time and if it still yielded an item
520 /// try to advance the second iterator at most one time.
522 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
524 /// [`unzip`]: Iterator::unzip
531 /// let a1 = [1, 2, 3];
532 /// let a2 = [4, 5, 6];
534 /// let mut iter = a1.iter().zip(a2.iter());
536 /// assert_eq!(iter.next(), Some((&1, &4)));
537 /// assert_eq!(iter.next(), Some((&2, &5)));
538 /// assert_eq!(iter.next(), Some((&3, &6)));
539 /// assert_eq!(iter.next(), None);
542 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
543 /// anything that can be converted into an [`Iterator`], not just an
544 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
545 /// [`IntoIterator`], and so can be passed to `zip()` directly:
548 /// let s1 = &[1, 2, 3];
549 /// let s2 = &[4, 5, 6];
551 /// let mut iter = s1.iter().zip(s2);
553 /// assert_eq!(iter.next(), Some((&1, &4)));
554 /// assert_eq!(iter.next(), Some((&2, &5)));
555 /// assert_eq!(iter.next(), Some((&3, &6)));
556 /// assert_eq!(iter.next(), None);
559 /// `zip()` is often used to zip an infinite iterator to a finite one.
560 /// This works because the finite iterator will eventually return [`None`],
561 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
564 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
566 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
568 /// assert_eq!((0, 'f'), enumerate[0]);
569 /// assert_eq!((0, 'f'), zipper[0]);
571 /// assert_eq!((1, 'o'), enumerate[1]);
572 /// assert_eq!((1, 'o'), zipper[1]);
574 /// assert_eq!((2, 'o'), enumerate[2]);
575 /// assert_eq!((2, 'o'), zipper[2]);
578 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
581 /// use std::iter::zip;
583 /// let a = [1, 2, 3];
584 /// let b = [2, 3, 4];
586 /// let mut zipped = zip(
587 /// a.into_iter().map(|x| x * 2).skip(1),
588 /// b.into_iter().map(|x| x * 2).skip(1),
591 /// assert_eq!(zipped.next(), Some((4, 6)));
592 /// assert_eq!(zipped.next(), Some((6, 8)));
593 /// assert_eq!(zipped.next(), None);
599 /// # let a = [1, 2, 3];
600 /// # let b = [2, 3, 4];
602 /// let mut zipped = a
606 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
608 /// # assert_eq!(zipped.next(), Some((4, 6)));
609 /// # assert_eq!(zipped.next(), Some((6, 8)));
610 /// # assert_eq!(zipped.next(), None);
613 /// [`enumerate`]: Iterator::enumerate
614 /// [`next`]: Iterator::next
615 /// [`zip`]: crate::iter::zip
617 #[stable(feature = "rust1", since = "1.0.0")]
618 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
623 Zip::new(self, other.into_iter())
626 /// Creates a new iterator which places a copy of `separator` between adjacent
627 /// items of the original iterator.
629 /// In case `separator` does not implement [`Clone`] or needs to be
630 /// computed every time, use [`intersperse_with`].
637 /// #![feature(iter_intersperse)]
639 /// let mut a = [0, 1, 2].iter().intersperse(&100);
640 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
641 /// assert_eq!(a.next(), Some(&100)); // The separator.
642 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
643 /// assert_eq!(a.next(), Some(&100)); // The separator.
644 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
645 /// assert_eq!(a.next(), None); // The iterator is finished.
648 /// `intersperse` can be very useful to join an iterator's items using a common element:
650 /// #![feature(iter_intersperse)]
652 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
653 /// assert_eq!(hello, "Hello World !");
656 /// [`Clone`]: crate::clone::Clone
657 /// [`intersperse_with`]: Iterator::intersperse_with
659 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
660 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
665 Intersperse::new(self, separator)
668 /// Creates a new iterator which places an item generated by `separator`
669 /// between adjacent items of the original iterator.
671 /// The closure will be called exactly once each time an item is placed
672 /// between two adjacent items from the underlying iterator; specifically,
673 /// the closure is not called if the underlying iterator yields less than
674 /// two items and after the last item is yielded.
676 /// If the iterator's item implements [`Clone`], it may be easier to use
684 /// #![feature(iter_intersperse)]
686 /// #[derive(PartialEq, Debug)]
687 /// struct NotClone(usize);
689 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
690 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
692 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
693 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
694 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
695 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
696 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
697 /// assert_eq!(it.next(), None); // The iterator is finished.
700 /// `intersperse_with` can be used in situations where the separator needs
703 /// #![feature(iter_intersperse)]
705 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
707 /// // The closure mutably borrows its context to generate an item.
708 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
709 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
711 /// let result = src.intersperse_with(separator).collect::<String>();
712 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
714 /// [`Clone`]: crate::clone::Clone
715 /// [`intersperse`]: Iterator::intersperse
717 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
718 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
721 G: FnMut() -> Self::Item,
723 IntersperseWith::new(self, separator)
726 /// Takes a closure and creates an iterator which calls that closure on each
729 /// `map()` transforms one iterator into another, by means of its argument:
730 /// something that implements [`FnMut`]. It produces a new iterator which
731 /// calls this closure on each element of the original iterator.
733 /// If you are good at thinking in types, you can think of `map()` like this:
734 /// If you have an iterator that gives you elements of some type `A`, and
735 /// you want an iterator of some other type `B`, you can use `map()`,
736 /// passing a closure that takes an `A` and returns a `B`.
738 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
739 /// lazy, it is best used when you're already working with other iterators.
740 /// If you're doing some sort of looping for a side effect, it's considered
741 /// more idiomatic to use [`for`] than `map()`.
743 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
744 /// [`FnMut`]: crate::ops::FnMut
751 /// let a = [1, 2, 3];
753 /// let mut iter = a.iter().map(|x| 2 * x);
755 /// assert_eq!(iter.next(), Some(2));
756 /// assert_eq!(iter.next(), Some(4));
757 /// assert_eq!(iter.next(), Some(6));
758 /// assert_eq!(iter.next(), None);
761 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
764 /// # #![allow(unused_must_use)]
765 /// // don't do this:
766 /// (0..5).map(|x| println!("{x}"));
768 /// // it won't even execute, as it is lazy. Rust will warn you about this.
770 /// // Instead, use for:
776 #[stable(feature = "rust1", since = "1.0.0")]
777 fn map<B, F>(self, f: F) -> Map<Self, F>
780 F: FnMut(Self::Item) -> B,
785 /// Calls a closure on each element of an iterator.
787 /// This is equivalent to using a [`for`] loop on the iterator, although
788 /// `break` and `continue` are not possible from a closure. It's generally
789 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
790 /// when processing items at the end of longer iterator chains. In some
791 /// cases `for_each` may also be faster than a loop, because it will use
792 /// internal iteration on adapters like `Chain`.
794 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
801 /// use std::sync::mpsc::channel;
803 /// let (tx, rx) = channel();
804 /// (0..5).map(|x| x * 2 + 1)
805 /// .for_each(move |x| tx.send(x).unwrap());
807 /// let v: Vec<_> = rx.iter().collect();
808 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
811 /// For such a small example, a `for` loop may be cleaner, but `for_each`
812 /// might be preferable to keep a functional style with longer iterators:
815 /// (0..5).flat_map(|x| x * 100 .. x * 110)
817 /// .filter(|&(i, x)| (i + x) % 3 == 0)
818 /// .for_each(|(i, x)| println!("{i}:{x}"));
821 #[stable(feature = "iterator_for_each", since = "1.21.0")]
822 fn for_each<F>(self, f: F)
825 F: FnMut(Self::Item),
828 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
829 move |(), item| f(item)
832 self.fold((), call(f));
835 /// Creates an iterator which uses a closure to determine if an element
836 /// should be yielded.
838 /// Given an element the closure must return `true` or `false`. The returned
839 /// iterator will yield only the elements for which the closure returns
847 /// let a = [0i32, 1, 2];
849 /// let mut iter = a.iter().filter(|x| x.is_positive());
851 /// assert_eq!(iter.next(), Some(&1));
852 /// assert_eq!(iter.next(), Some(&2));
853 /// assert_eq!(iter.next(), None);
856 /// Because the closure passed to `filter()` takes a reference, and many
857 /// iterators iterate over references, this leads to a possibly confusing
858 /// situation, where the type of the closure is a double reference:
861 /// let a = [0, 1, 2];
863 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
865 /// assert_eq!(iter.next(), Some(&2));
866 /// assert_eq!(iter.next(), None);
869 /// It's common to instead use destructuring on the argument to strip away
873 /// let a = [0, 1, 2];
875 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
877 /// assert_eq!(iter.next(), Some(&2));
878 /// assert_eq!(iter.next(), None);
884 /// let a = [0, 1, 2];
886 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
888 /// assert_eq!(iter.next(), Some(&2));
889 /// assert_eq!(iter.next(), None);
894 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
896 #[stable(feature = "rust1", since = "1.0.0")]
897 fn filter<P>(self, predicate: P) -> Filter<Self, P>
900 P: FnMut(&Self::Item) -> bool,
902 Filter::new(self, predicate)
905 /// Creates an iterator that both filters and maps.
907 /// The returned iterator yields only the `value`s for which the supplied
908 /// closure returns `Some(value)`.
910 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
911 /// concise. The example below shows how a `map().filter().map()` can be
912 /// shortened to a single call to `filter_map`.
914 /// [`filter`]: Iterator::filter
915 /// [`map`]: Iterator::map
922 /// let a = ["1", "two", "NaN", "four", "5"];
924 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
926 /// assert_eq!(iter.next(), Some(1));
927 /// assert_eq!(iter.next(), Some(5));
928 /// assert_eq!(iter.next(), None);
931 /// Here's the same example, but with [`filter`] and [`map`]:
934 /// let a = ["1", "two", "NaN", "four", "5"];
935 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
936 /// assert_eq!(iter.next(), Some(1));
937 /// assert_eq!(iter.next(), Some(5));
938 /// assert_eq!(iter.next(), None);
941 #[stable(feature = "rust1", since = "1.0.0")]
942 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
945 F: FnMut(Self::Item) -> Option<B>,
947 FilterMap::new(self, f)
950 /// Creates an iterator which gives the current iteration count as well as
953 /// The iterator returned yields pairs `(i, val)`, where `i` is the
954 /// current index of iteration and `val` is the value returned by the
957 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
958 /// different sized integer, the [`zip`] function provides similar
961 /// # Overflow Behavior
963 /// The method does no guarding against overflows, so enumerating more than
964 /// [`usize::MAX`] elements either produces the wrong result or panics. If
965 /// debug assertions are enabled, a panic is guaranteed.
969 /// The returned iterator might panic if the to-be-returned index would
970 /// overflow a [`usize`].
972 /// [`zip`]: Iterator::zip
977 /// let a = ['a', 'b', 'c'];
979 /// let mut iter = a.iter().enumerate();
981 /// assert_eq!(iter.next(), Some((0, &'a')));
982 /// assert_eq!(iter.next(), Some((1, &'b')));
983 /// assert_eq!(iter.next(), Some((2, &'c')));
984 /// assert_eq!(iter.next(), None);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 fn enumerate(self) -> Enumerate<Self>
995 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
996 /// to look at the next element of the iterator without consuming it. See
997 /// their documentation for more information.
999 /// Note that the underlying iterator is still advanced when [`peek`] or
1000 /// [`peek_mut`] are called for the first time: In order to retrieve the
1001 /// next element, [`next`] is called on the underlying iterator, hence any
1002 /// side effects (i.e. anything other than fetching the next value) of
1003 /// the [`next`] method will occur.
1011 /// let xs = [1, 2, 3];
1013 /// let mut iter = xs.iter().peekable();
1015 /// // peek() lets us see into the future
1016 /// assert_eq!(iter.peek(), Some(&&1));
1017 /// assert_eq!(iter.next(), Some(&1));
1019 /// assert_eq!(iter.next(), Some(&2));
1021 /// // we can peek() multiple times, the iterator won't advance
1022 /// assert_eq!(iter.peek(), Some(&&3));
1023 /// assert_eq!(iter.peek(), Some(&&3));
1025 /// assert_eq!(iter.next(), Some(&3));
1027 /// // after the iterator is finished, so is peek()
1028 /// assert_eq!(iter.peek(), None);
1029 /// assert_eq!(iter.next(), None);
1032 /// Using [`peek_mut`] to mutate the next item without advancing the
1036 /// let xs = [1, 2, 3];
1038 /// let mut iter = xs.iter().peekable();
1040 /// // `peek_mut()` lets us see into the future
1041 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
1042 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
1043 /// assert_eq!(iter.next(), Some(&1));
1045 /// if let Some(mut p) = iter.peek_mut() {
1046 /// assert_eq!(*p, &2);
1047 /// // put a value into the iterator
1051 /// // The value reappears as the iterator continues
1052 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
1054 /// [`peek`]: Peekable::peek
1055 /// [`peek_mut`]: Peekable::peek_mut
1056 /// [`next`]: Iterator::next
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 fn peekable(self) -> Peekable<Self>
1066 /// Creates an iterator that [`skip`]s elements based on a predicate.
1068 /// [`skip`]: Iterator::skip
1070 /// `skip_while()` takes a closure as an argument. It will call this
1071 /// closure on each element of the iterator, and ignore elements
1072 /// until it returns `false`.
1074 /// After `false` is returned, `skip_while()`'s job is over, and the
1075 /// rest of the elements are yielded.
1082 /// let a = [-1i32, 0, 1];
1084 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
1086 /// assert_eq!(iter.next(), Some(&0));
1087 /// assert_eq!(iter.next(), Some(&1));
1088 /// assert_eq!(iter.next(), None);
1091 /// Because the closure passed to `skip_while()` takes a reference, and many
1092 /// iterators iterate over references, this leads to a possibly confusing
1093 /// situation, where the type of the closure argument is a double reference:
1096 /// let a = [-1, 0, 1];
1098 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1100 /// assert_eq!(iter.next(), Some(&0));
1101 /// assert_eq!(iter.next(), Some(&1));
1102 /// assert_eq!(iter.next(), None);
1105 /// Stopping after an initial `false`:
1108 /// let a = [-1, 0, 1, -2];
1110 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1112 /// assert_eq!(iter.next(), Some(&0));
1113 /// assert_eq!(iter.next(), Some(&1));
1115 /// // while this would have been false, since we already got a false,
1116 /// // skip_while() isn't used any more
1117 /// assert_eq!(iter.next(), Some(&-2));
1119 /// assert_eq!(iter.next(), None);
1122 #[doc(alias = "drop_while")]
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1127 P: FnMut(&Self::Item) -> bool,
1129 SkipWhile::new(self, predicate)
1132 /// Creates an iterator that yields elements based on a predicate.
1134 /// `take_while()` takes a closure as an argument. It will call this
1135 /// closure on each element of the iterator, and yield elements
1136 /// while it returns `true`.
1138 /// After `false` is returned, `take_while()`'s job is over, and the
1139 /// rest of the elements are ignored.
1146 /// let a = [-1i32, 0, 1];
1148 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1150 /// assert_eq!(iter.next(), Some(&-1));
1151 /// assert_eq!(iter.next(), None);
1154 /// Because the closure passed to `take_while()` takes a reference, and many
1155 /// iterators iterate over references, this leads to a possibly confusing
1156 /// situation, where the type of the closure is a double reference:
1159 /// let a = [-1, 0, 1];
1161 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1163 /// assert_eq!(iter.next(), Some(&-1));
1164 /// assert_eq!(iter.next(), None);
1167 /// Stopping after an initial `false`:
1170 /// let a = [-1, 0, 1, -2];
1172 /// let mut iter = a.iter().take_while(|x| **x < 0);
1174 /// assert_eq!(iter.next(), Some(&-1));
1176 /// // We have more elements that are less than zero, but since we already
1177 /// // got a false, take_while() isn't used any more
1178 /// assert_eq!(iter.next(), None);
1181 /// Because `take_while()` needs to look at the value in order to see if it
1182 /// should be included or not, consuming iterators will see that it is
1186 /// let a = [1, 2, 3, 4];
1187 /// let mut iter = a.iter();
1189 /// let result: Vec<i32> = iter.by_ref()
1190 /// .take_while(|n| **n != 3)
1194 /// assert_eq!(result, &[1, 2]);
1196 /// let result: Vec<i32> = iter.cloned().collect();
1198 /// assert_eq!(result, &[4]);
1201 /// The `3` is no longer there, because it was consumed in order to see if
1202 /// the iteration should stop, but wasn't placed back into the iterator.
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1208 P: FnMut(&Self::Item) -> bool,
1210 TakeWhile::new(self, predicate)
1213 /// Creates an iterator that both yields elements based on a predicate and maps.
1215 /// `map_while()` takes a closure as an argument. It will call this
1216 /// closure on each element of the iterator, and yield elements
1217 /// while it returns [`Some(_)`][`Some`].
1224 /// let a = [-1i32, 4, 0, 1];
1226 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1228 /// assert_eq!(iter.next(), Some(-16));
1229 /// assert_eq!(iter.next(), Some(4));
1230 /// assert_eq!(iter.next(), None);
1233 /// Here's the same example, but with [`take_while`] and [`map`]:
1235 /// [`take_while`]: Iterator::take_while
1236 /// [`map`]: Iterator::map
1239 /// let a = [-1i32, 4, 0, 1];
1241 /// let mut iter = a.iter()
1242 /// .map(|x| 16i32.checked_div(*x))
1243 /// .take_while(|x| x.is_some())
1244 /// .map(|x| x.unwrap());
1246 /// assert_eq!(iter.next(), Some(-16));
1247 /// assert_eq!(iter.next(), Some(4));
1248 /// assert_eq!(iter.next(), None);
1251 /// Stopping after an initial [`None`]:
1254 /// let a = [0, 1, 2, -3, 4, 5, -6];
1256 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1257 /// let vec = iter.collect::<Vec<_>>();
1259 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1260 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1261 /// assert_eq!(vec, vec![0, 1, 2]);
1264 /// Because `map_while()` needs to look at the value in order to see if it
1265 /// should be included or not, consuming iterators will see that it is
1269 /// let a = [1, 2, -3, 4];
1270 /// let mut iter = a.iter();
1272 /// let result: Vec<u32> = iter.by_ref()
1273 /// .map_while(|n| u32::try_from(*n).ok())
1276 /// assert_eq!(result, &[1, 2]);
1278 /// let result: Vec<i32> = iter.cloned().collect();
1280 /// assert_eq!(result, &[4]);
1283 /// The `-3` is no longer there, because it was consumed in order to see if
1284 /// the iteration should stop, but wasn't placed back into the iterator.
1286 /// Note that unlike [`take_while`] this iterator is **not** fused.
1287 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1288 /// If you need fused iterator, use [`fuse`].
1290 /// [`fuse`]: Iterator::fuse
1292 #[stable(feature = "iter_map_while", since = "1.57.0")]
1293 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1296 P: FnMut(Self::Item) -> Option<B>,
1298 MapWhile::new(self, predicate)
1301 /// Creates an iterator that skips the first `n` elements.
1303 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1304 /// iterator is reached (whichever happens first). After that, all the remaining
1305 /// elements are yielded. In particular, if the original iterator is too short,
1306 /// then the returned iterator is empty.
1308 /// Rather than overriding this method directly, instead override the `nth` method.
1315 /// let a = [1, 2, 3];
1317 /// let mut iter = a.iter().skip(2);
1319 /// assert_eq!(iter.next(), Some(&3));
1320 /// assert_eq!(iter.next(), None);
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 fn skip(self, n: usize) -> Skip<Self>
1331 /// Creates an iterator that yields the first `n` elements, or fewer
1332 /// if the underlying iterator ends sooner.
1334 /// `take(n)` yields elements until `n` elements are yielded or the end of
1335 /// the iterator is reached (whichever happens first).
1336 /// The returned iterator is a prefix of length `n` if the original iterator
1337 /// contains at least `n` elements, otherwise it contains all of the
1338 /// (fewer than `n`) elements of the original iterator.
1345 /// let a = [1, 2, 3];
1347 /// let mut iter = a.iter().take(2);
1349 /// assert_eq!(iter.next(), Some(&1));
1350 /// assert_eq!(iter.next(), Some(&2));
1351 /// assert_eq!(iter.next(), None);
1354 /// `take()` is often used with an infinite iterator, to make it finite:
1357 /// let mut iter = (0..).take(3);
1359 /// assert_eq!(iter.next(), Some(0));
1360 /// assert_eq!(iter.next(), Some(1));
1361 /// assert_eq!(iter.next(), Some(2));
1362 /// assert_eq!(iter.next(), None);
1365 /// If less than `n` elements are available,
1366 /// `take` will limit itself to the size of the underlying iterator:
1370 /// let mut iter = v.into_iter().take(5);
1371 /// assert_eq!(iter.next(), Some(1));
1372 /// assert_eq!(iter.next(), Some(2));
1373 /// assert_eq!(iter.next(), None);
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 fn take(self, n: usize) -> Take<Self>
1384 /// An iterator adapter which, like [`fold`], holds internal state, but
1385 /// unlike [`fold`], produces a new iterator.
1387 /// [`fold`]: Iterator::fold
1389 /// `scan()` takes two arguments: an initial value which seeds the internal
1390 /// state, and a closure with two arguments, the first being a mutable
1391 /// reference to the internal state and the second an iterator element.
1392 /// The closure can assign to the internal state to share state between
1395 /// On iteration, the closure will be applied to each element of the
1396 /// iterator and the return value from the closure, an [`Option`], is
1397 /// returned by the `next` method. Thus the closure can return
1398 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1405 /// let a = [1, 2, 3, 4];
1407 /// let mut iter = a.iter().scan(1, |state, &x| {
1408 /// // each iteration, we'll multiply the state by the element ...
1409 /// *state = *state * x;
1411 /// // ... and terminate if the state exceeds 6
1415 /// // ... else yield the negation of the state
1419 /// assert_eq!(iter.next(), Some(-1));
1420 /// assert_eq!(iter.next(), Some(-2));
1421 /// assert_eq!(iter.next(), Some(-6));
1422 /// assert_eq!(iter.next(), None);
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1429 F: FnMut(&mut St, Self::Item) -> Option<B>,
1431 Scan::new(self, initial_state, f)
1434 /// Creates an iterator that works like map, but flattens nested structure.
1436 /// The [`map`] adapter is very useful, but only when the closure
1437 /// argument produces values. If it produces an iterator instead, there's
1438 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1441 /// You can think of `flat_map(f)` as the semantic equivalent
1442 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1444 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1445 /// one item for each element, and `flat_map()`'s closure returns an
1446 /// iterator for each element.
1448 /// [`map`]: Iterator::map
1449 /// [`flatten`]: Iterator::flatten
1456 /// let words = ["alpha", "beta", "gamma"];
1458 /// // chars() returns an iterator
1459 /// let merged: String = words.iter()
1460 /// .flat_map(|s| s.chars())
1462 /// assert_eq!(merged, "alphabetagamma");
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1470 F: FnMut(Self::Item) -> U,
1472 FlatMap::new(self, f)
1475 /// Creates an iterator that flattens nested structure.
1477 /// This is useful when you have an iterator of iterators or an iterator of
1478 /// things that can be turned into iterators and you want to remove one
1479 /// level of indirection.
1486 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1487 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1488 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1491 /// Mapping and then flattening:
1494 /// let words = ["alpha", "beta", "gamma"];
1496 /// // chars() returns an iterator
1497 /// let merged: String = words.iter()
1498 /// .map(|s| s.chars())
1501 /// assert_eq!(merged, "alphabetagamma");
1504 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1505 /// in this case since it conveys intent more clearly:
1508 /// let words = ["alpha", "beta", "gamma"];
1510 /// // chars() returns an iterator
1511 /// let merged: String = words.iter()
1512 /// .flat_map(|s| s.chars())
1514 /// assert_eq!(merged, "alphabetagamma");
1517 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1520 /// let options = vec![Some(123), Some(321), None, Some(231)];
1521 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1522 /// assert_eq!(flattened_options, vec![123, 321, 231]);
1524 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1525 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1526 /// assert_eq!(flattened_results, vec![123, 321, 231]);
1529 /// Flattening only removes one level of nesting at a time:
1532 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1534 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1535 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1537 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1538 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1541 /// Here we see that `flatten()` does not perform a "deep" flatten.
1542 /// Instead, only one level of nesting is removed. That is, if you
1543 /// `flatten()` a three-dimensional array, the result will be
1544 /// two-dimensional and not one-dimensional. To get a one-dimensional
1545 /// structure, you have to `flatten()` again.
1547 /// [`flat_map()`]: Iterator::flat_map
1549 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1550 fn flatten(self) -> Flatten<Self>
1553 Self::Item: IntoIterator,
1558 /// Creates an iterator which ends after the first [`None`].
1560 /// After an iterator returns [`None`], future calls may or may not yield
1561 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1562 /// [`None`] is given, it will always return [`None`] forever.
1564 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1565 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1566 /// if the [`FusedIterator`] trait is improperly implemented.
1568 /// [`Some(T)`]: Some
1569 /// [`FusedIterator`]: crate::iter::FusedIterator
1576 /// // an iterator which alternates between Some and None
1577 /// struct Alternate {
1581 /// impl Iterator for Alternate {
1582 /// type Item = i32;
1584 /// fn next(&mut self) -> Option<i32> {
1585 /// let val = self.state;
1586 /// self.state = self.state + 1;
1588 /// // if it's even, Some(i32), else None
1589 /// if val % 2 == 0 {
1597 /// let mut iter = Alternate { state: 0 };
1599 /// // we can see our iterator going back and forth
1600 /// assert_eq!(iter.next(), Some(0));
1601 /// assert_eq!(iter.next(), None);
1602 /// assert_eq!(iter.next(), Some(2));
1603 /// assert_eq!(iter.next(), None);
1605 /// // however, once we fuse it...
1606 /// let mut iter = iter.fuse();
1608 /// assert_eq!(iter.next(), Some(4));
1609 /// assert_eq!(iter.next(), None);
1611 /// // it will always return `None` after the first time.
1612 /// assert_eq!(iter.next(), None);
1613 /// assert_eq!(iter.next(), None);
1614 /// assert_eq!(iter.next(), None);
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 fn fuse(self) -> Fuse<Self>
1625 /// Does something with each element of an iterator, passing the value on.
1627 /// When using iterators, you'll often chain several of them together.
1628 /// While working on such code, you might want to check out what's
1629 /// happening at various parts in the pipeline. To do that, insert
1630 /// a call to `inspect()`.
1632 /// It's more common for `inspect()` to be used as a debugging tool than to
1633 /// exist in your final code, but applications may find it useful in certain
1634 /// situations when errors need to be logged before being discarded.
1641 /// let a = [1, 4, 2, 3];
1643 /// // this iterator sequence is complex.
1644 /// let sum = a.iter()
1646 /// .filter(|x| x % 2 == 0)
1647 /// .fold(0, |sum, i| sum + i);
1649 /// println!("{sum}");
1651 /// // let's add some inspect() calls to investigate what's happening
1652 /// let sum = a.iter()
1654 /// .inspect(|x| println!("about to filter: {x}"))
1655 /// .filter(|x| x % 2 == 0)
1656 /// .inspect(|x| println!("made it through filter: {x}"))
1657 /// .fold(0, |sum, i| sum + i);
1659 /// println!("{sum}");
1662 /// This will print:
1666 /// about to filter: 1
1667 /// about to filter: 4
1668 /// made it through filter: 4
1669 /// about to filter: 2
1670 /// made it through filter: 2
1671 /// about to filter: 3
1675 /// Logging errors before discarding them:
1678 /// let lines = ["1", "2", "a"];
1680 /// let sum: i32 = lines
1682 /// .map(|line| line.parse::<i32>())
1683 /// .inspect(|num| {
1684 /// if let Err(ref e) = *num {
1685 /// println!("Parsing error: {e}");
1688 /// .filter_map(Result::ok)
1691 /// println!("Sum: {sum}");
1694 /// This will print:
1697 /// Parsing error: invalid digit found in string
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1705 F: FnMut(&Self::Item),
1707 Inspect::new(self, f)
1710 /// Borrows an iterator, rather than consuming it.
1712 /// This is useful to allow applying iterator adapters while still
1713 /// retaining ownership of the original iterator.
1720 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1722 /// // Take the first two words.
1723 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1724 /// assert_eq!(hello_world, vec!["hello", "world"]);
1726 /// // Collect the rest of the words.
1727 /// // We can only do this because we used `by_ref` earlier.
1728 /// let of_rust: Vec<_> = words.collect();
1729 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 fn by_ref(&mut self) -> &mut Self
1739 /// Transforms an iterator into a collection.
1741 /// `collect()` can take anything iterable, and turn it into a relevant
1742 /// collection. This is one of the more powerful methods in the standard
1743 /// library, used in a variety of contexts.
1745 /// The most basic pattern in which `collect()` is used is to turn one
1746 /// collection into another. You take a collection, call [`iter`] on it,
1747 /// do a bunch of transformations, and then `collect()` at the end.
1749 /// `collect()` can also create instances of types that are not typical
1750 /// collections. For example, a [`String`] can be built from [`char`]s,
1751 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1752 /// into `Result<Collection<T>, E>`. See the examples below for more.
1754 /// Because `collect()` is so general, it can cause problems with type
1755 /// inference. As such, `collect()` is one of the few times you'll see
1756 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1757 /// helps the inference algorithm understand specifically which collection
1758 /// you're trying to collect into.
1765 /// let a = [1, 2, 3];
1767 /// let doubled: Vec<i32> = a.iter()
1768 /// .map(|&x| x * 2)
1771 /// assert_eq!(vec![2, 4, 6], doubled);
1774 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1775 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1777 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1780 /// use std::collections::VecDeque;
1782 /// let a = [1, 2, 3];
1784 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1786 /// assert_eq!(2, doubled[0]);
1787 /// assert_eq!(4, doubled[1]);
1788 /// assert_eq!(6, doubled[2]);
1791 /// Using the 'turbofish' instead of annotating `doubled`:
1794 /// let a = [1, 2, 3];
1796 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1798 /// assert_eq!(vec![2, 4, 6], doubled);
1801 /// Because `collect()` only cares about what you're collecting into, you can
1802 /// still use a partial type hint, `_`, with the turbofish:
1805 /// let a = [1, 2, 3];
1807 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1809 /// assert_eq!(vec![2, 4, 6], doubled);
1812 /// Using `collect()` to make a [`String`]:
1815 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1817 /// let hello: String = chars.iter()
1818 /// .map(|&x| x as u8)
1819 /// .map(|x| (x + 1) as char)
1822 /// assert_eq!("hello", hello);
1825 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1826 /// see if any of them failed:
1829 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1831 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1833 /// // gives us the first error
1834 /// assert_eq!(Err("nope"), result);
1836 /// let results = [Ok(1), Ok(3)];
1838 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1840 /// // gives us the list of answers
1841 /// assert_eq!(Ok(vec![1, 3]), result);
1844 /// [`iter`]: Iterator::next
1845 /// [`String`]: ../../std/string/struct.String.html
1846 /// [`char`]: type@char
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1850 #[cfg_attr(not(test), rustc_diagnostic_item = "iterator_collect_fn")]
1851 fn collect<B: FromIterator<Self::Item>>(self) -> B
1855 FromIterator::from_iter(self)
1858 /// Fallibly transforms an iterator into a collection, short circuiting if
1859 /// a failure is encountered.
1861 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
1862 /// conversions during collection. Its main use case is simplifying conversions from
1863 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
1864 /// types (e.g. [`Result`]).
1866 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
1867 /// only the inner type produced on `Try::Output` must implement it. Concretely,
1868 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
1869 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
1871 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
1872 /// may continue to be used, in which case it will continue iterating starting after the element that
1873 /// triggered the failure. See the last example below for an example of how this works.
1876 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
1878 /// #![feature(iterator_try_collect)]
1880 /// let u = vec![Some(1), Some(2), Some(3)];
1881 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1882 /// assert_eq!(v, Some(vec![1, 2, 3]));
1885 /// Failing to collect in the same way:
1887 /// #![feature(iterator_try_collect)]
1889 /// let u = vec![Some(1), Some(2), None, Some(3)];
1890 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1891 /// assert_eq!(v, None);
1894 /// A similar example, but with `Result`:
1896 /// #![feature(iterator_try_collect)]
1898 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
1899 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1900 /// assert_eq!(v, Ok(vec![1, 2, 3]));
1902 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
1903 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1904 /// assert_eq!(v, Err(()));
1907 /// Finally, even [`ControlFlow`] works, despite the fact that it
1908 /// doesn't implement [`FromIterator`]. Note also that the iterator can
1909 /// continue to be used, even if a failure is encountered:
1912 /// #![feature(iterator_try_collect)]
1914 /// use core::ops::ControlFlow::{Break, Continue};
1916 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
1917 /// let mut it = u.into_iter();
1919 /// let v = it.try_collect::<Vec<_>>();
1920 /// assert_eq!(v, Break(3));
1922 /// let v = it.try_collect::<Vec<_>>();
1923 /// assert_eq!(v, Continue(vec![4, 5]));
1926 /// [`collect`]: Iterator::collect
1928 #[unstable(feature = "iterator_try_collect", issue = "94047")]
1929 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
1932 <Self as Iterator>::Item: Try,
1933 <<Self as Iterator>::Item as Try>::Residual: Residual<B>,
1934 B: FromIterator<<Self::Item as Try>::Output>,
1936 try_process(ByRefSized(self), |i| i.collect())
1939 /// Collects all the items from an iterator into a collection.
1941 /// This method consumes the iterator and adds all its items to the
1942 /// passed collection. The collection is then returned, so the call chain
1943 /// can be continued.
1945 /// This is useful when you already have a collection and wants to add
1946 /// the iterator items to it.
1948 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
1949 /// but instead of being called on a collection, it's called on an iterator.
1956 /// #![feature(iter_collect_into)]
1958 /// let a = [1, 2, 3];
1959 /// let mut vec: Vec::<i32> = vec![0, 1];
1961 /// a.iter().map(|&x| x * 2).collect_into(&mut vec);
1962 /// a.iter().map(|&x| x * 10).collect_into(&mut vec);
1964 /// assert_eq!(vec![0, 1, 2, 4, 6, 10, 20, 30], vec);
1967 /// `Vec` can have a manual set capacity to avoid reallocating it:
1970 /// #![feature(iter_collect_into)]
1972 /// let a = [1, 2, 3];
1973 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
1975 /// a.iter().map(|&x| x * 2).collect_into(&mut vec);
1976 /// a.iter().map(|&x| x * 10).collect_into(&mut vec);
1978 /// assert_eq!(6, vec.capacity());
1979 /// println!("{:?}", vec);
1982 /// The returned mutable reference can be used to continue the call chain:
1985 /// #![feature(iter_collect_into)]
1987 /// let a = [1, 2, 3];
1988 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
1990 /// let count = a.iter().collect_into(&mut vec).iter().count();
1992 /// assert_eq!(count, vec.len());
1993 /// println!("Vec len is {}", count);
1995 /// let count = a.iter().collect_into(&mut vec).iter().count();
1997 /// assert_eq!(count, vec.len());
1998 /// println!("Vec len now is {}", count);
2001 #[unstable(feature = "iter_collect_into", reason = "new API", issue = "94780")]
2002 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2006 collection.extend(self);
2010 /// Consumes an iterator, creating two collections from it.
2012 /// The predicate passed to `partition()` can return `true`, or `false`.
2013 /// `partition()` returns a pair, all of the elements for which it returned
2014 /// `true`, and all of the elements for which it returned `false`.
2016 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2018 /// [`is_partitioned()`]: Iterator::is_partitioned
2019 /// [`partition_in_place()`]: Iterator::partition_in_place
2026 /// let a = [1, 2, 3];
2028 /// let (even, odd): (Vec<_>, Vec<_>) = a
2030 /// .partition(|n| n % 2 == 0);
2032 /// assert_eq!(even, vec![2]);
2033 /// assert_eq!(odd, vec![1, 3]);
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 fn partition<B, F>(self, f: F) -> (B, B)
2039 B: Default + Extend<Self::Item>,
2040 F: FnMut(&Self::Item) -> bool,
2043 fn extend<'a, T, B: Extend<T>>(
2044 mut f: impl FnMut(&T) -> bool + 'a,
2047 ) -> impl FnMut((), T) + 'a {
2052 right.extend_one(x);
2057 let mut left: B = Default::default();
2058 let mut right: B = Default::default();
2060 self.fold((), extend(f, &mut left, &mut right));
2065 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2066 /// such that all those that return `true` precede all those that return `false`.
2067 /// Returns the number of `true` elements found.
2069 /// The relative order of partitioned items is not maintained.
2071 /// # Current implementation
2073 /// Current algorithms tries finding the first element for which the predicate evaluates
2074 /// to false, and the last element for which it evaluates to true and repeatedly swaps them.
2076 /// Time complexity: *O*(*n*)
2078 /// See also [`is_partitioned()`] and [`partition()`].
2080 /// [`is_partitioned()`]: Iterator::is_partitioned
2081 /// [`partition()`]: Iterator::partition
2086 /// #![feature(iter_partition_in_place)]
2088 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2090 /// // Partition in-place between evens and odds
2091 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
2093 /// assert_eq!(i, 3);
2094 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
2095 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
2097 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
2098 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2100 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2101 P: FnMut(&T) -> bool,
2103 // FIXME: should we worry about the count overflowing? The only way to have more than
2104 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2106 // These closure "factory" functions exist to avoid genericity in `Self`.
2110 predicate: &'a mut impl FnMut(&T) -> bool,
2111 true_count: &'a mut usize,
2112 ) -> impl FnMut(&&mut T) -> bool + 'a {
2114 let p = predicate(&**x);
2115 *true_count += p as usize;
2121 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2122 move |x| predicate(&**x)
2125 // Repeatedly find the first `false` and swap it with the last `true`.
2126 let mut true_count = 0;
2127 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2128 if let Some(tail) = self.rfind(is_true(predicate)) {
2129 crate::mem::swap(head, tail);
2138 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2139 /// such that all those that return `true` precede all those that return `false`.
2141 /// See also [`partition()`] and [`partition_in_place()`].
2143 /// [`partition()`]: Iterator::partition
2144 /// [`partition_in_place()`]: Iterator::partition_in_place
2149 /// #![feature(iter_is_partitioned)]
2151 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2152 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2154 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
2155 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2158 P: FnMut(Self::Item) -> bool,
2160 // Either all items test `true`, or the first clause stops at `false`
2161 // and we check that there are no more `true` items after that.
2162 self.all(&mut predicate) || !self.any(predicate)
2165 /// An iterator method that applies a function as long as it returns
2166 /// successfully, producing a single, final value.
2168 /// `try_fold()` takes two arguments: an initial value, and a closure with
2169 /// two arguments: an 'accumulator', and an element. The closure either
2170 /// returns successfully, with the value that the accumulator should have
2171 /// for the next iteration, or it returns failure, with an error value that
2172 /// is propagated back to the caller immediately (short-circuiting).
2174 /// The initial value is the value the accumulator will have on the first
2175 /// call. If applying the closure succeeded against every element of the
2176 /// iterator, `try_fold()` returns the final accumulator as success.
2178 /// Folding is useful whenever you have a collection of something, and want
2179 /// to produce a single value from it.
2181 /// # Note to Implementors
2183 /// Several of the other (forward) methods have default implementations in
2184 /// terms of this one, so try to implement this explicitly if it can
2185 /// do something better than the default `for` loop implementation.
2187 /// In particular, try to have this call `try_fold()` on the internal parts
2188 /// from which this iterator is composed. If multiple calls are needed,
2189 /// the `?` operator may be convenient for chaining the accumulator value
2190 /// along, but beware any invariants that need to be upheld before those
2191 /// early returns. This is a `&mut self` method, so iteration needs to be
2192 /// resumable after hitting an error here.
2199 /// let a = [1, 2, 3];
2201 /// // the checked sum of all of the elements of the array
2202 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
2204 /// assert_eq!(sum, Some(6));
2207 /// Short-circuiting:
2210 /// let a = [10, 20, 30, 100, 40, 50];
2211 /// let mut it = a.iter();
2213 /// // This sum overflows when adding the 100 element
2214 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
2215 /// assert_eq!(sum, None);
2217 /// // Because it short-circuited, the remaining elements are still
2218 /// // available through the iterator.
2219 /// assert_eq!(it.len(), 2);
2220 /// assert_eq!(it.next(), Some(&40));
2223 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2227 /// use std::ops::ControlFlow;
2229 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2230 /// if let Some(next) = prev.checked_add(x) {
2231 /// ControlFlow::Continue(next)
2233 /// ControlFlow::Break(prev)
2236 /// assert_eq!(triangular, ControlFlow::Break(120));
2238 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2239 /// if let Some(next) = prev.checked_add(x) {
2240 /// ControlFlow::Continue(next)
2242 /// ControlFlow::Break(prev)
2245 /// assert_eq!(triangular, ControlFlow::Continue(435));
2248 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2249 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2252 F: FnMut(B, Self::Item) -> R,
2255 let mut accum = init;
2256 while let Some(x) = self.next() {
2257 accum = f(accum, x)?;
2262 /// An iterator method that applies a fallible function to each item in the
2263 /// iterator, stopping at the first error and returning that error.
2265 /// This can also be thought of as the fallible form of [`for_each()`]
2266 /// or as the stateless version of [`try_fold()`].
2268 /// [`for_each()`]: Iterator::for_each
2269 /// [`try_fold()`]: Iterator::try_fold
2274 /// use std::fs::rename;
2275 /// use std::io::{stdout, Write};
2276 /// use std::path::Path;
2278 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2280 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2281 /// assert!(res.is_ok());
2283 /// let mut it = data.iter().cloned();
2284 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2285 /// assert!(res.is_err());
2286 /// // It short-circuited, so the remaining items are still in the iterator:
2287 /// assert_eq!(it.next(), Some("stale_bread.json"));
2290 /// The [`ControlFlow`] type can be used with this method for the situations
2291 /// in which you'd use `break` and `continue` in a normal loop:
2294 /// use std::ops::ControlFlow;
2296 /// let r = (2..100).try_for_each(|x| {
2297 /// if 323 % x == 0 {
2298 /// return ControlFlow::Break(x)
2301 /// ControlFlow::Continue(())
2303 /// assert_eq!(r, ControlFlow::Break(17));
2306 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2307 fn try_for_each<F, R>(&mut self, f: F) -> R
2310 F: FnMut(Self::Item) -> R,
2311 R: Try<Output = ()>,
2314 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2318 self.try_fold((), call(f))
2321 /// Folds every element into an accumulator by applying an operation,
2322 /// returning the final result.
2324 /// `fold()` takes two arguments: an initial value, and a closure with two
2325 /// arguments: an 'accumulator', and an element. The closure returns the value that
2326 /// the accumulator should have for the next iteration.
2328 /// The initial value is the value the accumulator will have on the first
2331 /// After applying this closure to every element of the iterator, `fold()`
2332 /// returns the accumulator.
2334 /// This operation is sometimes called 'reduce' or 'inject'.
2336 /// Folding is useful whenever you have a collection of something, and want
2337 /// to produce a single value from it.
2339 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2340 /// might not terminate for infinite iterators, even on traits for which a
2341 /// result is determinable in finite time.
2343 /// Note: [`reduce()`] can be used to use the first element as the initial
2344 /// value, if the accumulator type and item type is the same.
2346 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2347 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2348 /// operators like `-` the order will affect the final result.
2349 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2351 /// # Note to Implementors
2353 /// Several of the other (forward) methods have default implementations in
2354 /// terms of this one, so try to implement this explicitly if it can
2355 /// do something better than the default `for` loop implementation.
2357 /// In particular, try to have this call `fold()` on the internal parts
2358 /// from which this iterator is composed.
2365 /// let a = [1, 2, 3];
2367 /// // the sum of all of the elements of the array
2368 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2370 /// assert_eq!(sum, 6);
2373 /// Let's walk through each step of the iteration here:
2375 /// | element | acc | x | result |
2376 /// |---------|-----|---|--------|
2378 /// | 1 | 0 | 1 | 1 |
2379 /// | 2 | 1 | 2 | 3 |
2380 /// | 3 | 3 | 3 | 6 |
2382 /// And so, our final result, `6`.
2384 /// This example demonstrates the left-associative nature of `fold()`:
2385 /// it builds a string, starting with an initial value
2386 /// and continuing with each element from the front until the back:
2389 /// let numbers = [1, 2, 3, 4, 5];
2391 /// let zero = "0".to_string();
2393 /// let result = numbers.iter().fold(zero, |acc, &x| {
2394 /// format!("({acc} + {x})")
2397 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2399 /// It's common for people who haven't used iterators a lot to
2400 /// use a `for` loop with a list of things to build up a result. Those
2401 /// can be turned into `fold()`s:
2403 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2406 /// let numbers = [1, 2, 3, 4, 5];
2408 /// let mut result = 0;
2411 /// for i in &numbers {
2412 /// result = result + i;
2416 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2418 /// // they're the same
2419 /// assert_eq!(result, result2);
2422 /// [`reduce()`]: Iterator::reduce
2423 #[doc(alias = "inject", alias = "foldl")]
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2429 F: FnMut(B, Self::Item) -> B,
2431 let mut accum = init;
2432 while let Some(x) = self.next() {
2433 accum = f(accum, x);
2438 /// Reduces the elements to a single one, by repeatedly applying a reducing
2441 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2442 /// result of the reduction.
2444 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2445 /// For iterators with at least one element, this is the same as [`fold()`]
2446 /// with the first element of the iterator as the initial accumulator value, folding
2447 /// every subsequent element into it.
2449 /// [`fold()`]: Iterator::fold
2454 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
2455 /// assert_eq!(reduced, 45);
2457 /// // Which is equivalent to doing it with `fold`:
2458 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2459 /// assert_eq!(reduced, folded);
2462 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2463 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2466 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2468 let first = self.next()?;
2469 Some(self.fold(first, f))
2472 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2473 /// closure returns a failure, the failure is propagated back to the caller immediately.
2475 /// The return type of this method depends on the return type of the closure. If the closure
2476 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2477 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2478 /// `Option<Option<Self::Item>>`.
2480 /// When called on an empty iterator, this function will return either `Some(None)` or
2481 /// `Ok(None)` depending on the type of the provided closure.
2483 /// For iterators with at least one element, this is essentially the same as calling
2484 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2486 /// [`try_fold()`]: Iterator::try_fold
2490 /// Safely calculate the sum of a series of numbers:
2493 /// #![feature(iterator_try_reduce)]
2495 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2496 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2497 /// assert_eq!(sum, Some(Some(58)));
2500 /// Determine when a reduction short circuited:
2503 /// #![feature(iterator_try_reduce)]
2505 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2506 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2507 /// assert_eq!(sum, None);
2510 /// Determine when a reduction was not performed because there are no elements:
2513 /// #![feature(iterator_try_reduce)]
2515 /// let numbers: Vec<usize> = Vec::new();
2516 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2517 /// assert_eq!(sum, Some(None));
2520 /// Use a [`Result`] instead of an [`Option`]:
2523 /// #![feature(iterator_try_reduce)]
2525 /// let numbers = vec!["1", "2", "3", "4", "5"];
2526 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2527 /// numbers.into_iter().try_reduce(|x, y| {
2528 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2530 /// assert_eq!(max, Ok(Some("5")));
2533 #[unstable(feature = "iterator_try_reduce", reason = "new API", issue = "87053")]
2534 fn try_reduce<F, R>(&mut self, f: F) -> ChangeOutputType<R, Option<R::Output>>
2537 F: FnMut(Self::Item, Self::Item) -> R,
2538 R: Try<Output = Self::Item>,
2539 R::Residual: Residual<Option<Self::Item>>,
2541 let first = match self.next() {
2543 None => return Try::from_output(None),
2546 match self.try_fold(first, f).branch() {
2547 ControlFlow::Break(r) => FromResidual::from_residual(r),
2548 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2552 /// Tests if every element of the iterator matches a predicate.
2554 /// `all()` takes a closure that returns `true` or `false`. It applies
2555 /// this closure to each element of the iterator, and if they all return
2556 /// `true`, then so does `all()`. If any of them return `false`, it
2557 /// returns `false`.
2559 /// `all()` is short-circuiting; in other words, it will stop processing
2560 /// as soon as it finds a `false`, given that no matter what else happens,
2561 /// the result will also be `false`.
2563 /// An empty iterator returns `true`.
2570 /// let a = [1, 2, 3];
2572 /// assert!(a.iter().all(|&x| x > 0));
2574 /// assert!(!a.iter().all(|&x| x > 2));
2577 /// Stopping at the first `false`:
2580 /// let a = [1, 2, 3];
2582 /// let mut iter = a.iter();
2584 /// assert!(!iter.all(|&x| x != 2));
2586 /// // we can still use `iter`, as there are more elements.
2587 /// assert_eq!(iter.next(), Some(&3));
2590 #[stable(feature = "rust1", since = "1.0.0")]
2591 fn all<F>(&mut self, f: F) -> bool
2594 F: FnMut(Self::Item) -> bool,
2597 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2599 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2602 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2605 /// Tests if any element of the iterator matches a predicate.
2607 /// `any()` takes a closure that returns `true` or `false`. It applies
2608 /// this closure to each element of the iterator, and if any of them return
2609 /// `true`, then so does `any()`. If they all return `false`, it
2610 /// returns `false`.
2612 /// `any()` is short-circuiting; in other words, it will stop processing
2613 /// as soon as it finds a `true`, given that no matter what else happens,
2614 /// the result will also be `true`.
2616 /// An empty iterator returns `false`.
2623 /// let a = [1, 2, 3];
2625 /// assert!(a.iter().any(|&x| x > 0));
2627 /// assert!(!a.iter().any(|&x| x > 5));
2630 /// Stopping at the first `true`:
2633 /// let a = [1, 2, 3];
2635 /// let mut iter = a.iter();
2637 /// assert!(iter.any(|&x| x != 2));
2639 /// // we can still use `iter`, as there are more elements.
2640 /// assert_eq!(iter.next(), Some(&2));
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 fn any<F>(&mut self, f: F) -> bool
2647 F: FnMut(Self::Item) -> bool,
2650 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2652 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2656 self.try_fold((), check(f)) == ControlFlow::BREAK
2659 /// Searches for an element of an iterator that satisfies a predicate.
2661 /// `find()` takes a closure that returns `true` or `false`. It applies
2662 /// this closure to each element of the iterator, and if any of them return
2663 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2664 /// `false`, it returns [`None`].
2666 /// `find()` is short-circuiting; in other words, it will stop processing
2667 /// as soon as the closure returns `true`.
2669 /// Because `find()` takes a reference, and many iterators iterate over
2670 /// references, this leads to a possibly confusing situation where the
2671 /// argument is a double reference. You can see this effect in the
2672 /// examples below, with `&&x`.
2674 /// If you need the index of the element, see [`position()`].
2676 /// [`Some(element)`]: Some
2677 /// [`position()`]: Iterator::position
2684 /// let a = [1, 2, 3];
2686 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2688 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2691 /// Stopping at the first `true`:
2694 /// let a = [1, 2, 3];
2696 /// let mut iter = a.iter();
2698 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2700 /// // we can still use `iter`, as there are more elements.
2701 /// assert_eq!(iter.next(), Some(&3));
2704 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2706 #[stable(feature = "rust1", since = "1.0.0")]
2707 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2710 P: FnMut(&Self::Item) -> bool,
2713 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2715 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2719 self.try_fold((), check(predicate)).break_value()
2722 /// Applies function to the elements of iterator and returns
2723 /// the first non-none result.
2725 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2730 /// let a = ["lol", "NaN", "2", "5"];
2732 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2734 /// assert_eq!(first_number, Some(2));
2737 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2738 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2741 F: FnMut(Self::Item) -> Option<B>,
2744 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2745 move |(), x| match f(x) {
2746 Some(x) => ControlFlow::Break(x),
2747 None => ControlFlow::CONTINUE,
2751 self.try_fold((), check(f)).break_value()
2754 /// Applies function to the elements of iterator and returns
2755 /// the first true result or the first error.
2757 /// The return type of this method depends on the return type of the closure.
2758 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
2759 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
2764 /// #![feature(try_find)]
2766 /// let a = ["1", "2", "lol", "NaN", "5"];
2768 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2769 /// Ok(s.parse::<i32>()? == search)
2772 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2773 /// assert_eq!(result, Ok(Some(&"2")));
2775 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2776 /// assert!(result.is_err());
2779 /// This also supports other types which implement `Try`, not just `Result`.
2781 /// #![feature(try_find)]
2783 /// use std::num::NonZeroU32;
2784 /// let a = [3, 5, 7, 4, 9, 0, 11];
2785 /// let result = a.iter().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2786 /// assert_eq!(result, Some(Some(&4)));
2787 /// let result = a.iter().take(3).try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2788 /// assert_eq!(result, Some(None));
2789 /// let result = a.iter().rev().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2790 /// assert_eq!(result, None);
2793 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2794 fn try_find<F, R>(&mut self, f: F) -> ChangeOutputType<R, Option<Self::Item>>
2797 F: FnMut(&Self::Item) -> R,
2798 R: Try<Output = bool>,
2799 R::Residual: Residual<Option<Self::Item>>,
2803 mut f: impl FnMut(&I) -> V,
2804 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
2806 V: Try<Output = bool, Residual = R>,
2807 R: Residual<Option<I>>,
2809 move |(), x| match f(&x).branch() {
2810 ControlFlow::Continue(false) => ControlFlow::CONTINUE,
2811 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
2812 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
2816 match self.try_fold((), check(f)) {
2817 ControlFlow::Break(x) => x,
2818 ControlFlow::Continue(()) => Try::from_output(None),
2822 /// Searches for an element in an iterator, returning its index.
2824 /// `position()` takes a closure that returns `true` or `false`. It applies
2825 /// this closure to each element of the iterator, and if one of them
2826 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2827 /// them return `false`, it returns [`None`].
2829 /// `position()` is short-circuiting; in other words, it will stop
2830 /// processing as soon as it finds a `true`.
2832 /// # Overflow Behavior
2834 /// The method does no guarding against overflows, so if there are more
2835 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2836 /// result or panics. If debug assertions are enabled, a panic is
2841 /// This function might panic if the iterator has more than `usize::MAX`
2842 /// non-matching elements.
2844 /// [`Some(index)`]: Some
2851 /// let a = [1, 2, 3];
2853 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2855 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2858 /// Stopping at the first `true`:
2861 /// let a = [1, 2, 3, 4];
2863 /// let mut iter = a.iter();
2865 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2867 /// // we can still use `iter`, as there are more elements.
2868 /// assert_eq!(iter.next(), Some(&3));
2870 /// // The returned index depends on iterator state
2871 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2875 #[stable(feature = "rust1", since = "1.0.0")]
2876 fn position<P>(&mut self, predicate: P) -> Option<usize>
2879 P: FnMut(Self::Item) -> bool,
2883 mut predicate: impl FnMut(T) -> bool,
2884 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2885 #[rustc_inherit_overflow_checks]
2887 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2891 self.try_fold(0, check(predicate)).break_value()
2894 /// Searches for an element in an iterator from the right, returning its
2897 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2898 /// this closure to each element of the iterator, starting from the end,
2899 /// and if one of them returns `true`, then `rposition()` returns
2900 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2902 /// `rposition()` is short-circuiting; in other words, it will stop
2903 /// processing as soon as it finds a `true`.
2905 /// [`Some(index)`]: Some
2912 /// let a = [1, 2, 3];
2914 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2916 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2919 /// Stopping at the first `true`:
2922 /// let a = [-1, 2, 3, 4];
2924 /// let mut iter = a.iter();
2926 /// assert_eq!(iter.rposition(|&x| x >= 2), Some(3));
2928 /// // we can still use `iter`, as there are more elements.
2929 /// assert_eq!(iter.next(), Some(&-1));
2932 #[stable(feature = "rust1", since = "1.0.0")]
2933 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2935 P: FnMut(Self::Item) -> bool,
2936 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2938 // No need for an overflow check here, because `ExactSizeIterator`
2939 // implies that the number of elements fits into a `usize`.
2942 mut predicate: impl FnMut(T) -> bool,
2943 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2946 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2951 self.try_rfold(n, check(predicate)).break_value()
2954 /// Returns the maximum element of an iterator.
2956 /// If several elements are equally maximum, the last element is
2957 /// returned. If the iterator is empty, [`None`] is returned.
2959 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2960 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2963 /// [2.4, f32::NAN, 1.3]
2965 /// .reduce(f32::max)
2976 /// let a = [1, 2, 3];
2977 /// let b: Vec<u32> = Vec::new();
2979 /// assert_eq!(a.iter().max(), Some(&3));
2980 /// assert_eq!(b.iter().max(), None);
2983 #[stable(feature = "rust1", since = "1.0.0")]
2984 fn max(self) -> Option<Self::Item>
2989 self.max_by(Ord::cmp)
2992 /// Returns the minimum element of an iterator.
2994 /// If several elements are equally minimum, the first element is returned.
2995 /// If the iterator is empty, [`None`] is returned.
2997 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2998 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3001 /// [2.4, f32::NAN, 1.3]
3003 /// .reduce(f32::min)
3014 /// let a = [1, 2, 3];
3015 /// let b: Vec<u32> = Vec::new();
3017 /// assert_eq!(a.iter().min(), Some(&1));
3018 /// assert_eq!(b.iter().min(), None);
3021 #[stable(feature = "rust1", since = "1.0.0")]
3022 fn min(self) -> Option<Self::Item>
3027 self.min_by(Ord::cmp)
3030 /// Returns the element that gives the maximum value from the
3031 /// specified function.
3033 /// If several elements are equally maximum, the last element is
3034 /// returned. If the iterator is empty, [`None`] is returned.
3039 /// let a = [-3_i32, 0, 1, 5, -10];
3040 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
3043 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3044 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3047 F: FnMut(&Self::Item) -> B,
3050 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3055 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3059 let (_, x) = self.map(key(f)).max_by(compare)?;
3063 /// Returns the element that gives the maximum value with respect to the
3064 /// specified comparison function.
3066 /// If several elements are equally maximum, the last element is
3067 /// returned. If the iterator is empty, [`None`] is returned.
3072 /// let a = [-3_i32, 0, 1, 5, -10];
3073 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3076 #[stable(feature = "iter_max_by", since = "1.15.0")]
3077 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3080 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3083 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3084 move |x, y| cmp::max_by(x, y, &mut compare)
3087 self.reduce(fold(compare))
3090 /// Returns the element that gives the minimum value from the
3091 /// specified function.
3093 /// If several elements are equally minimum, the first element is
3094 /// returned. If the iterator is empty, [`None`] is returned.
3099 /// let a = [-3_i32, 0, 1, 5, -10];
3100 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
3103 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3104 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3107 F: FnMut(&Self::Item) -> B,
3110 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3115 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3119 let (_, x) = self.map(key(f)).min_by(compare)?;
3123 /// Returns the element that gives the minimum value with respect to the
3124 /// specified comparison function.
3126 /// If several elements are equally minimum, the first element is
3127 /// returned. If the iterator is empty, [`None`] is returned.
3132 /// let a = [-3_i32, 0, 1, 5, -10];
3133 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3136 #[stable(feature = "iter_min_by", since = "1.15.0")]
3137 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3140 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3143 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3144 move |x, y| cmp::min_by(x, y, &mut compare)
3147 self.reduce(fold(compare))
3150 /// Reverses an iterator's direction.
3152 /// Usually, iterators iterate from left to right. After using `rev()`,
3153 /// an iterator will instead iterate from right to left.
3155 /// This is only possible if the iterator has an end, so `rev()` only
3156 /// works on [`DoubleEndedIterator`]s.
3161 /// let a = [1, 2, 3];
3163 /// let mut iter = a.iter().rev();
3165 /// assert_eq!(iter.next(), Some(&3));
3166 /// assert_eq!(iter.next(), Some(&2));
3167 /// assert_eq!(iter.next(), Some(&1));
3169 /// assert_eq!(iter.next(), None);
3172 #[doc(alias = "reverse")]
3173 #[stable(feature = "rust1", since = "1.0.0")]
3174 fn rev(self) -> Rev<Self>
3176 Self: Sized + DoubleEndedIterator,
3181 /// Converts an iterator of pairs into a pair of containers.
3183 /// `unzip()` consumes an entire iterator of pairs, producing two
3184 /// collections: one from the left elements of the pairs, and one
3185 /// from the right elements.
3187 /// This function is, in some sense, the opposite of [`zip`].
3189 /// [`zip`]: Iterator::zip
3196 /// let a = [(1, 2), (3, 4), (5, 6)];
3198 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
3200 /// assert_eq!(left, [1, 3, 5]);
3201 /// assert_eq!(right, [2, 4, 6]);
3203 /// // you can also unzip multiple nested tuples at once
3204 /// let a = [(1, (2, 3)), (4, (5, 6))];
3206 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.iter().cloned().unzip();
3207 /// assert_eq!(x, [1, 4]);
3208 /// assert_eq!(y, [2, 5]);
3209 /// assert_eq!(z, [3, 6]);
3211 #[stable(feature = "rust1", since = "1.0.0")]
3212 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3214 FromA: Default + Extend<A>,
3215 FromB: Default + Extend<B>,
3216 Self: Sized + Iterator<Item = (A, B)>,
3218 let mut unzipped: (FromA, FromB) = Default::default();
3219 unzipped.extend(self);
3223 /// Creates an iterator which copies all of its elements.
3225 /// This is useful when you have an iterator over `&T`, but you need an
3226 /// iterator over `T`.
3233 /// let a = [1, 2, 3];
3235 /// let v_copied: Vec<_> = a.iter().copied().collect();
3237 /// // copied is the same as .map(|&x| x)
3238 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3240 /// assert_eq!(v_copied, vec![1, 2, 3]);
3241 /// assert_eq!(v_map, vec![1, 2, 3]);
3243 #[stable(feature = "iter_copied", since = "1.36.0")]
3244 fn copied<'a, T: 'a>(self) -> Copied<Self>
3246 Self: Sized + Iterator<Item = &'a T>,
3252 /// Creates an iterator which [`clone`]s all of its elements.
3254 /// This is useful when you have an iterator over `&T`, but you need an
3255 /// iterator over `T`.
3257 /// There is no guarantee whatsoever about the `clone` method actually
3258 /// being called *or* optimized away. So code should not depend on
3261 /// [`clone`]: Clone::clone
3268 /// let a = [1, 2, 3];
3270 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3272 /// // cloned is the same as .map(|&x| x), for integers
3273 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3275 /// assert_eq!(v_cloned, vec![1, 2, 3]);
3276 /// assert_eq!(v_map, vec![1, 2, 3]);
3279 /// To get the best performance, try to clone late:
3282 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3283 /// // don't do this:
3284 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3285 /// assert_eq!(&[vec![23]], &slower[..]);
3286 /// // instead call `cloned` late
3287 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3288 /// assert_eq!(&[vec![23]], &faster[..]);
3290 #[stable(feature = "rust1", since = "1.0.0")]
3291 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
3293 Self: Sized + Iterator<Item = &'a T>,
3299 /// Repeats an iterator endlessly.
3301 /// Instead of stopping at [`None`], the iterator will instead start again,
3302 /// from the beginning. After iterating again, it will start at the
3303 /// beginning again. And again. And again. Forever. Note that in case the
3304 /// original iterator is empty, the resulting iterator will also be empty.
3311 /// let a = [1, 2, 3];
3313 /// let mut it = a.iter().cycle();
3315 /// assert_eq!(it.next(), Some(&1));
3316 /// assert_eq!(it.next(), Some(&2));
3317 /// assert_eq!(it.next(), Some(&3));
3318 /// assert_eq!(it.next(), Some(&1));
3319 /// assert_eq!(it.next(), Some(&2));
3320 /// assert_eq!(it.next(), Some(&3));
3321 /// assert_eq!(it.next(), Some(&1));
3323 #[stable(feature = "rust1", since = "1.0.0")]
3325 fn cycle(self) -> Cycle<Self>
3327 Self: Sized + Clone,
3332 /// Returns an iterator over `N` elements of the iterator at a time.
3334 /// The chunks do not overlap. If `N` does not divide the length of the
3335 /// iterator, then the last up to `N-1` elements will be omitted and can be
3336 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3337 /// function of the iterator.
3341 /// Panics if `N` is 0.
3348 /// #![feature(iter_array_chunks)]
3350 /// let mut iter = "lorem".chars().array_chunks();
3351 /// assert_eq!(iter.next(), Some(['l', 'o']));
3352 /// assert_eq!(iter.next(), Some(['r', 'e']));
3353 /// assert_eq!(iter.next(), None);
3354 /// assert_eq!(iter.into_remainder().unwrap().as_slice(), &['m']);
3358 /// #![feature(iter_array_chunks)]
3360 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3361 /// // ^-----^ ^------^
3362 /// for [x, y, z] in data.iter().array_chunks() {
3363 /// assert_eq!(x + y + z, 4);
3367 #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
3368 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3372 ArrayChunks::new(self)
3375 /// Sums the elements of an iterator.
3377 /// Takes each element, adds them together, and returns the result.
3379 /// An empty iterator returns the zero value of the type.
3383 /// When calling `sum()` and a primitive integer type is being returned, this
3384 /// method will panic if the computation overflows and debug assertions are
3392 /// let a = [1, 2, 3];
3393 /// let sum: i32 = a.iter().sum();
3395 /// assert_eq!(sum, 6);
3397 #[stable(feature = "iter_arith", since = "1.11.0")]
3398 fn sum<S>(self) -> S
3406 /// Iterates over the entire iterator, multiplying all the elements
3408 /// An empty iterator returns the one value of the type.
3412 /// When calling `product()` and a primitive integer type is being returned,
3413 /// method will panic if the computation overflows and debug assertions are
3419 /// fn factorial(n: u32) -> u32 {
3420 /// (1..=n).product()
3422 /// assert_eq!(factorial(0), 1);
3423 /// assert_eq!(factorial(1), 1);
3424 /// assert_eq!(factorial(5), 120);
3426 #[stable(feature = "iter_arith", since = "1.11.0")]
3427 fn product<P>(self) -> P
3430 P: Product<Self::Item>,
3432 Product::product(self)
3435 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3441 /// use std::cmp::Ordering;
3443 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3444 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3445 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3447 #[stable(feature = "iter_order", since = "1.5.0")]
3448 fn cmp<I>(self, other: I) -> Ordering
3450 I: IntoIterator<Item = Self::Item>,
3454 self.cmp_by(other, |x, y| x.cmp(&y))
3457 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3458 /// of another with respect to the specified comparison function.
3465 /// #![feature(iter_order_by)]
3467 /// use std::cmp::Ordering;
3469 /// let xs = [1, 2, 3, 4];
3470 /// let ys = [1, 4, 9, 16];
3472 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3473 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3474 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3476 #[unstable(feature = "iter_order_by", issue = "64295")]
3477 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3481 F: FnMut(Self::Item, I::Item) -> Ordering,
3484 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3486 F: FnMut(X, Y) -> Ordering,
3488 move |x, y| match cmp(x, y) {
3489 Ordering::Equal => ControlFlow::CONTINUE,
3490 non_eq => ControlFlow::Break(non_eq),
3494 match iter_compare(self, other.into_iter(), compare(cmp)) {
3495 ControlFlow::Continue(ord) => ord,
3496 ControlFlow::Break(ord) => ord,
3500 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3506 /// use std::cmp::Ordering;
3508 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3509 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3510 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3512 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3514 #[stable(feature = "iter_order", since = "1.5.0")]
3515 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3518 Self::Item: PartialOrd<I::Item>,
3521 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3524 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3525 /// of another with respect to the specified comparison function.
3532 /// #![feature(iter_order_by)]
3534 /// use std::cmp::Ordering;
3536 /// let xs = [1.0, 2.0, 3.0, 4.0];
3537 /// let ys = [1.0, 4.0, 9.0, 16.0];
3540 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3541 /// Some(Ordering::Less)
3544 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3545 /// Some(Ordering::Equal)
3548 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3549 /// Some(Ordering::Greater)
3552 #[unstable(feature = "iter_order_by", issue = "64295")]
3553 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3557 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3560 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3562 F: FnMut(X, Y) -> Option<Ordering>,
3564 move |x, y| match partial_cmp(x, y) {
3565 Some(Ordering::Equal) => ControlFlow::CONTINUE,
3566 non_eq => ControlFlow::Break(non_eq),
3570 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3571 ControlFlow::Continue(ord) => Some(ord),
3572 ControlFlow::Break(ord) => ord,
3576 /// Determines if the elements of this [`Iterator`] are equal to those of
3582 /// assert_eq!([1].iter().eq([1].iter()), true);
3583 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3585 #[stable(feature = "iter_order", since = "1.5.0")]
3586 fn eq<I>(self, other: I) -> bool
3589 Self::Item: PartialEq<I::Item>,
3592 self.eq_by(other, |x, y| x == y)
3595 /// Determines if the elements of this [`Iterator`] are equal to those of
3596 /// another with respect to the specified equality function.
3603 /// #![feature(iter_order_by)]
3605 /// let xs = [1, 2, 3, 4];
3606 /// let ys = [1, 4, 9, 16];
3608 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3610 #[unstable(feature = "iter_order_by", issue = "64295")]
3611 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3615 F: FnMut(Self::Item, I::Item) -> bool,
3618 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3620 F: FnMut(X, Y) -> bool,
3623 if eq(x, y) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
3627 match iter_compare(self, other.into_iter(), compare(eq)) {
3628 ControlFlow::Continue(ord) => ord == Ordering::Equal,
3629 ControlFlow::Break(()) => false,
3633 /// Determines if the elements of this [`Iterator`] are unequal to those of
3639 /// assert_eq!([1].iter().ne([1].iter()), false);
3640 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3642 #[stable(feature = "iter_order", since = "1.5.0")]
3643 fn ne<I>(self, other: I) -> bool
3646 Self::Item: PartialEq<I::Item>,
3652 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3653 /// less than those of another.
3658 /// assert_eq!([1].iter().lt([1].iter()), false);
3659 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3660 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3661 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3663 #[stable(feature = "iter_order", since = "1.5.0")]
3664 fn lt<I>(self, other: I) -> bool
3667 Self::Item: PartialOrd<I::Item>,
3670 self.partial_cmp(other) == Some(Ordering::Less)
3673 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3674 /// less or equal to those of another.
3679 /// assert_eq!([1].iter().le([1].iter()), true);
3680 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3681 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3682 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3684 #[stable(feature = "iter_order", since = "1.5.0")]
3685 fn le<I>(self, other: I) -> bool
3688 Self::Item: PartialOrd<I::Item>,
3691 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3694 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3695 /// greater than those of another.
3700 /// assert_eq!([1].iter().gt([1].iter()), false);
3701 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3702 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3703 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3705 #[stable(feature = "iter_order", since = "1.5.0")]
3706 fn gt<I>(self, other: I) -> bool
3709 Self::Item: PartialOrd<I::Item>,
3712 self.partial_cmp(other) == Some(Ordering::Greater)
3715 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3716 /// greater than or equal to those of another.
3721 /// assert_eq!([1].iter().ge([1].iter()), true);
3722 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3723 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3724 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3726 #[stable(feature = "iter_order", since = "1.5.0")]
3727 fn ge<I>(self, other: I) -> bool
3730 Self::Item: PartialOrd<I::Item>,
3733 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3736 /// Checks if the elements of this iterator are sorted.
3738 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3739 /// iterator yields exactly zero or one element, `true` is returned.
3741 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3742 /// implies that this function returns `false` if any two consecutive items are not
3748 /// #![feature(is_sorted)]
3750 /// assert!([1, 2, 2, 9].iter().is_sorted());
3751 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3752 /// assert!([0].iter().is_sorted());
3753 /// assert!(std::iter::empty::<i32>().is_sorted());
3754 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3757 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3758 fn is_sorted(self) -> bool
3761 Self::Item: PartialOrd,
3763 self.is_sorted_by(PartialOrd::partial_cmp)
3766 /// Checks if the elements of this iterator are sorted using the given comparator function.
3768 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3769 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3770 /// [`is_sorted`]; see its documentation for more information.
3775 /// #![feature(is_sorted)]
3777 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3778 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3779 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3780 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3781 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3784 /// [`is_sorted`]: Iterator::is_sorted
3785 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3786 fn is_sorted_by<F>(mut self, compare: F) -> bool
3789 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3794 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3795 ) -> impl FnMut(T) -> bool + 'a {
3797 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3805 let mut last = match self.next() {
3807 None => return true,
3810 self.all(check(&mut last, compare))
3813 /// Checks if the elements of this iterator are sorted using the given key extraction
3816 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3817 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3818 /// its documentation for more information.
3820 /// [`is_sorted`]: Iterator::is_sorted
3825 /// #![feature(is_sorted)]
3827 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3828 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3831 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3832 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3835 F: FnMut(Self::Item) -> K,
3838 self.map(f).is_sorted()
3841 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
3842 // The unusual name is to avoid name collisions in method resolution
3846 #[unstable(feature = "trusted_random_access", issue = "none")]
3847 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3849 Self: TrustedRandomAccessNoCoerce,
3851 unreachable!("Always specialized");
3855 /// Compares two iterators element-wise using the given function.
3857 /// If `ControlFlow::CONTINUE` is returned from the function, the comparison moves on to the next
3858 /// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
3859 /// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
3860 /// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
3863 /// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
3864 /// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
3866 fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
3870 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
3873 fn compare<'a, B, X, T>(
3875 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
3876 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
3880 move |x| match b.next() {
3881 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
3882 Some(y) => f(x, y).map_break(ControlFlow::Break),
3886 match a.try_for_each(compare(&mut b, f)) {
3887 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
3888 None => Ordering::Equal,
3889 Some(_) => Ordering::Less,
3891 ControlFlow::Break(x) => x,
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 impl<I: Iterator + ?Sized> Iterator for &mut I {
3897 type Item = I::Item;
3899 fn next(&mut self) -> Option<I::Item> {
3902 fn size_hint(&self) -> (usize, Option<usize>) {
3903 (**self).size_hint()
3905 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3906 (**self).advance_by(n)
3908 fn nth(&mut self, n: usize) -> Option<Self::Item> {