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 #[stable(feature = "rust1", since = "1.0.0")]
72 /// Advances the iterator and returns the next value.
74 /// Returns [`None`] when iteration is finished. Individual iterator
75 /// implementations may choose to resume iteration, and so calling `next()`
76 /// again may or may not eventually start returning [`Some(Item)`] again at some
79 /// [`Some(Item)`]: Some
86 /// let a = [1, 2, 3];
88 /// let mut iter = a.iter();
90 /// // A call to next() returns the next value...
91 /// assert_eq!(Some(&1), iter.next());
92 /// assert_eq!(Some(&2), iter.next());
93 /// assert_eq!(Some(&3), iter.next());
95 /// // ... and then None once it's over.
96 /// assert_eq!(None, iter.next());
98 /// // More calls may or may not return `None`. Here, they always will.
99 /// assert_eq!(None, iter.next());
100 /// assert_eq!(None, iter.next());
103 #[stable(feature = "rust1", since = "1.0.0")]
104 fn next(&mut self) -> Option<Self::Item>;
106 /// Advances the iterator and returns an array containing the next `N` values.
108 /// If there are not enough elements to fill the array then `Err` is returned
109 /// containing an iterator over the remaining elements.
116 /// #![feature(iter_next_chunk)]
118 /// let mut iter = "lorem".chars();
120 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
121 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
122 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
125 /// Split a string and get the first three items.
128 /// #![feature(iter_next_chunk)]
130 /// let quote = "not all those who wander are lost";
131 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
132 /// assert_eq!(first, "not");
133 /// assert_eq!(second, "all");
134 /// assert_eq!(third, "those");
137 #[unstable(feature = "iter_next_chunk", reason = "recently added", issue = "98326")]
138 fn next_chunk<const N: usize>(
140 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
144 array::iter_next_chunk(self)
147 /// Returns the bounds on the remaining length of the iterator.
149 /// Specifically, `size_hint()` returns a tuple where the first element
150 /// is the lower bound, and the second element is the upper bound.
152 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
153 /// A [`None`] here means that either there is no known upper bound, or the
154 /// upper bound is larger than [`usize`].
156 /// # Implementation notes
158 /// It is not enforced that an iterator implementation yields the declared
159 /// number of elements. A buggy iterator may yield less than the lower bound
160 /// or more than the upper bound of elements.
162 /// `size_hint()` is primarily intended to be used for optimizations such as
163 /// reserving space for the elements of the iterator, but must not be
164 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
165 /// implementation of `size_hint()` should not lead to memory safety
168 /// That said, the implementation should provide a correct estimation,
169 /// because otherwise it would be a violation of the trait's protocol.
171 /// The default implementation returns <code>(0, [None])</code> which is correct for any
179 /// let a = [1, 2, 3];
180 /// let mut iter = a.iter();
182 /// assert_eq!((3, Some(3)), iter.size_hint());
183 /// let _ = iter.next();
184 /// assert_eq!((2, Some(2)), iter.size_hint());
187 /// A more complex example:
190 /// // The even numbers in the range of zero to nine.
191 /// let iter = (0..10).filter(|x| x % 2 == 0);
193 /// // We might iterate from zero to ten times. Knowing that it's five
194 /// // exactly wouldn't be possible without executing filter().
195 /// assert_eq!((0, Some(10)), iter.size_hint());
197 /// // Let's add five more numbers with chain()
198 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
200 /// // now both bounds are increased by five
201 /// assert_eq!((5, Some(15)), iter.size_hint());
204 /// Returning `None` for an upper bound:
207 /// // an infinite iterator has no upper bound
208 /// // and the maximum possible lower bound
211 /// assert_eq!((usize::MAX, None), iter.size_hint());
214 #[stable(feature = "rust1", since = "1.0.0")]
215 fn size_hint(&self) -> (usize, Option<usize>) {
219 /// Consumes the iterator, counting the number of iterations and returning it.
221 /// This method will call [`next`] repeatedly until [`None`] is encountered,
222 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
223 /// called at least once even if the iterator does not have any elements.
225 /// [`next`]: Iterator::next
227 /// # Overflow Behavior
229 /// The method does no guarding against overflows, so counting elements of
230 /// an iterator with more than [`usize::MAX`] elements either produces the
231 /// wrong result or panics. If debug assertions are enabled, a panic is
236 /// This function might panic if the iterator has more than [`usize::MAX`]
244 /// let a = [1, 2, 3];
245 /// assert_eq!(a.iter().count(), 3);
247 /// let a = [1, 2, 3, 4, 5];
248 /// assert_eq!(a.iter().count(), 5);
251 #[stable(feature = "rust1", since = "1.0.0")]
252 fn count(self) -> usize
258 #[rustc_inherit_overflow_checks]
259 |count, _| count + 1,
263 /// Consumes the iterator, returning the last element.
265 /// This method will evaluate the iterator until it returns [`None`]. While
266 /// doing so, it keeps track of the current element. After [`None`] is
267 /// returned, `last()` will then return the last element it saw.
274 /// let a = [1, 2, 3];
275 /// assert_eq!(a.iter().last(), Some(&3));
277 /// let a = [1, 2, 3, 4, 5];
278 /// assert_eq!(a.iter().last(), Some(&5));
281 #[stable(feature = "rust1", since = "1.0.0")]
282 fn last(self) -> Option<Self::Item>
287 fn some<T>(_: Option<T>, x: T) -> Option<T> {
291 self.fold(None, some)
294 /// Advances the iterator by `n` elements.
296 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
297 /// times until [`None`] is encountered.
299 /// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
300 /// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
301 /// of elements the iterator is advanced by before running out of elements (i.e. the
302 /// length of the iterator). Note that `k` is always less than `n`.
304 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
305 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
306 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
308 /// [`Flatten`]: crate::iter::Flatten
309 /// [`next`]: Iterator::next
316 /// #![feature(iter_advance_by)]
318 /// let a = [1, 2, 3, 4];
319 /// let mut iter = a.iter();
321 /// assert_eq!(iter.advance_by(2), Ok(()));
322 /// assert_eq!(iter.next(), Some(&3));
323 /// assert_eq!(iter.advance_by(0), Ok(()));
324 /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
327 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
328 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
330 self.next().ok_or(i)?;
335 /// Returns the `n`th element of the iterator.
337 /// Like most indexing operations, the count starts from zero, so `nth(0)`
338 /// returns the first value, `nth(1)` the second, and so on.
340 /// Note that all preceding elements, as well as the returned element, will be
341 /// consumed from the iterator. That means that the preceding elements will be
342 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
343 /// will return different elements.
345 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
353 /// let a = [1, 2, 3];
354 /// assert_eq!(a.iter().nth(1), Some(&2));
357 /// Calling `nth()` multiple times doesn't rewind the iterator:
360 /// let a = [1, 2, 3];
362 /// let mut iter = a.iter();
364 /// assert_eq!(iter.nth(1), Some(&2));
365 /// assert_eq!(iter.nth(1), None);
368 /// Returning `None` if there are less than `n + 1` elements:
371 /// let a = [1, 2, 3];
372 /// assert_eq!(a.iter().nth(10), None);
375 #[stable(feature = "rust1", since = "1.0.0")]
376 fn nth(&mut self, n: usize) -> Option<Self::Item> {
377 self.advance_by(n).ok()?;
381 /// Creates an iterator starting at the same point, but stepping by
382 /// the given amount at each iteration.
384 /// Note 1: The first element of the iterator will always be returned,
385 /// regardless of the step given.
387 /// Note 2: The time at which ignored elements are pulled is not fixed.
388 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
389 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
390 /// `advance_n_and_return_first(&mut self, step)`,
391 /// `advance_n_and_return_first(&mut self, step)`, …
392 /// Which way is used may change for some iterators for performance reasons.
393 /// The second way will advance the iterator earlier and may consume more items.
395 /// `advance_n_and_return_first` is the equivalent of:
397 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
401 /// let next = iter.next();
411 /// The method will panic if the given step is `0`.
418 /// let a = [0, 1, 2, 3, 4, 5];
419 /// let mut iter = a.iter().step_by(2);
421 /// assert_eq!(iter.next(), Some(&0));
422 /// assert_eq!(iter.next(), Some(&2));
423 /// assert_eq!(iter.next(), Some(&4));
424 /// assert_eq!(iter.next(), None);
427 #[stable(feature = "iterator_step_by", since = "1.28.0")]
428 fn step_by(self, step: usize) -> StepBy<Self>
432 StepBy::new(self, step)
435 /// Takes two iterators and creates a new iterator over both in sequence.
437 /// `chain()` will return a new iterator which will first iterate over
438 /// values from the first iterator and then over values from the second
441 /// In other words, it links two iterators together, in a chain. 🔗
443 /// [`once`] is commonly used to adapt a single value into a chain of
444 /// other kinds of iteration.
451 /// let a1 = [1, 2, 3];
452 /// let a2 = [4, 5, 6];
454 /// let mut iter = a1.iter().chain(a2.iter());
456 /// assert_eq!(iter.next(), Some(&1));
457 /// assert_eq!(iter.next(), Some(&2));
458 /// assert_eq!(iter.next(), Some(&3));
459 /// assert_eq!(iter.next(), Some(&4));
460 /// assert_eq!(iter.next(), Some(&5));
461 /// assert_eq!(iter.next(), Some(&6));
462 /// assert_eq!(iter.next(), None);
465 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
466 /// anything that can be converted into an [`Iterator`], not just an
467 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
468 /// [`IntoIterator`], and so can be passed to `chain()` directly:
471 /// let s1 = &[1, 2, 3];
472 /// let s2 = &[4, 5, 6];
474 /// let mut iter = s1.iter().chain(s2);
476 /// assert_eq!(iter.next(), Some(&1));
477 /// assert_eq!(iter.next(), Some(&2));
478 /// assert_eq!(iter.next(), Some(&3));
479 /// assert_eq!(iter.next(), Some(&4));
480 /// assert_eq!(iter.next(), Some(&5));
481 /// assert_eq!(iter.next(), Some(&6));
482 /// assert_eq!(iter.next(), None);
485 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
489 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
490 /// use std::os::windows::ffi::OsStrExt;
491 /// s.encode_wide().chain(std::iter::once(0)).collect()
495 /// [`once`]: crate::iter::once
496 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
498 #[stable(feature = "rust1", since = "1.0.0")]
499 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
502 U: IntoIterator<Item = Self::Item>,
504 Chain::new(self, other.into_iter())
507 /// 'Zips up' two iterators into a single iterator of pairs.
509 /// `zip()` returns a new iterator that will iterate over two other
510 /// iterators, returning a tuple where the first element comes from the
511 /// first iterator, and the second element comes from the second iterator.
513 /// In other words, it zips two iterators together, into a single one.
515 /// If either iterator returns [`None`], [`next`] from the zipped iterator
516 /// will return [`None`].
517 /// If the zipped iterator has no more elements to return then each further attempt to advance
518 /// it will first try to advance the first iterator at most one time and if it still yielded an item
519 /// try to advance the second iterator at most one time.
521 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
523 /// [`unzip`]: Iterator::unzip
530 /// let a1 = [1, 2, 3];
531 /// let a2 = [4, 5, 6];
533 /// let mut iter = a1.iter().zip(a2.iter());
535 /// assert_eq!(iter.next(), Some((&1, &4)));
536 /// assert_eq!(iter.next(), Some((&2, &5)));
537 /// assert_eq!(iter.next(), Some((&3, &6)));
538 /// assert_eq!(iter.next(), None);
541 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
542 /// anything that can be converted into an [`Iterator`], not just an
543 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
544 /// [`IntoIterator`], and so can be passed to `zip()` directly:
547 /// let s1 = &[1, 2, 3];
548 /// let s2 = &[4, 5, 6];
550 /// let mut iter = s1.iter().zip(s2);
552 /// assert_eq!(iter.next(), Some((&1, &4)));
553 /// assert_eq!(iter.next(), Some((&2, &5)));
554 /// assert_eq!(iter.next(), Some((&3, &6)));
555 /// assert_eq!(iter.next(), None);
558 /// `zip()` is often used to zip an infinite iterator to a finite one.
559 /// This works because the finite iterator will eventually return [`None`],
560 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
563 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
565 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
567 /// assert_eq!((0, 'f'), enumerate[0]);
568 /// assert_eq!((0, 'f'), zipper[0]);
570 /// assert_eq!((1, 'o'), enumerate[1]);
571 /// assert_eq!((1, 'o'), zipper[1]);
573 /// assert_eq!((2, 'o'), enumerate[2]);
574 /// assert_eq!((2, 'o'), zipper[2]);
577 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
580 /// use std::iter::zip;
582 /// let a = [1, 2, 3];
583 /// let b = [2, 3, 4];
585 /// let mut zipped = zip(
586 /// a.into_iter().map(|x| x * 2).skip(1),
587 /// b.into_iter().map(|x| x * 2).skip(1),
590 /// assert_eq!(zipped.next(), Some((4, 6)));
591 /// assert_eq!(zipped.next(), Some((6, 8)));
592 /// assert_eq!(zipped.next(), None);
598 /// # let a = [1, 2, 3];
599 /// # let b = [2, 3, 4];
601 /// let mut zipped = a
605 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
607 /// # assert_eq!(zipped.next(), Some((4, 6)));
608 /// # assert_eq!(zipped.next(), Some((6, 8)));
609 /// # assert_eq!(zipped.next(), None);
612 /// [`enumerate`]: Iterator::enumerate
613 /// [`next`]: Iterator::next
614 /// [`zip`]: crate::iter::zip
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
622 Zip::new(self, other.into_iter())
625 /// Creates a new iterator which places a copy of `separator` between adjacent
626 /// items of the original iterator.
628 /// In case `separator` does not implement [`Clone`] or needs to be
629 /// computed every time, use [`intersperse_with`].
636 /// #![feature(iter_intersperse)]
638 /// let mut a = [0, 1, 2].iter().intersperse(&100);
639 /// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
640 /// assert_eq!(a.next(), Some(&100)); // The separator.
641 /// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
642 /// assert_eq!(a.next(), Some(&100)); // The separator.
643 /// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
644 /// assert_eq!(a.next(), None); // The iterator is finished.
647 /// `intersperse` can be very useful to join an iterator's items using a common element:
649 /// #![feature(iter_intersperse)]
651 /// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
652 /// assert_eq!(hello, "Hello World !");
655 /// [`Clone`]: crate::clone::Clone
656 /// [`intersperse_with`]: Iterator::intersperse_with
658 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
659 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
664 Intersperse::new(self, separator)
667 /// Creates a new iterator which places an item generated by `separator`
668 /// between adjacent items of the original iterator.
670 /// The closure will be called exactly once each time an item is placed
671 /// between two adjacent items from the underlying iterator; specifically,
672 /// the closure is not called if the underlying iterator yields less than
673 /// two items and after the last item is yielded.
675 /// If the iterator's item implements [`Clone`], it may be easier to use
683 /// #![feature(iter_intersperse)]
685 /// #[derive(PartialEq, Debug)]
686 /// struct NotClone(usize);
688 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
689 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
691 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
692 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
693 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
694 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
695 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
696 /// assert_eq!(it.next(), None); // The iterator is finished.
699 /// `intersperse_with` can be used in situations where the separator needs
702 /// #![feature(iter_intersperse)]
704 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
706 /// // The closure mutably borrows its context to generate an item.
707 /// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
708 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
710 /// let result = src.intersperse_with(separator).collect::<String>();
711 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
713 /// [`Clone`]: crate::clone::Clone
714 /// [`intersperse`]: Iterator::intersperse
716 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
717 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
720 G: FnMut() -> Self::Item,
722 IntersperseWith::new(self, separator)
725 /// Takes a closure and creates an iterator which calls that closure on each
728 /// `map()` transforms one iterator into another, by means of its argument:
729 /// something that implements [`FnMut`]. It produces a new iterator which
730 /// calls this closure on each element of the original iterator.
732 /// If you are good at thinking in types, you can think of `map()` like this:
733 /// If you have an iterator that gives you elements of some type `A`, and
734 /// you want an iterator of some other type `B`, you can use `map()`,
735 /// passing a closure that takes an `A` and returns a `B`.
737 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
738 /// lazy, it is best used when you're already working with other iterators.
739 /// If you're doing some sort of looping for a side effect, it's considered
740 /// more idiomatic to use [`for`] than `map()`.
742 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
743 /// [`FnMut`]: crate::ops::FnMut
750 /// let a = [1, 2, 3];
752 /// let mut iter = a.iter().map(|x| 2 * x);
754 /// assert_eq!(iter.next(), Some(2));
755 /// assert_eq!(iter.next(), Some(4));
756 /// assert_eq!(iter.next(), Some(6));
757 /// assert_eq!(iter.next(), None);
760 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
763 /// # #![allow(unused_must_use)]
764 /// // don't do this:
765 /// (0..5).map(|x| println!("{x}"));
767 /// // it won't even execute, as it is lazy. Rust will warn you about this.
769 /// // Instead, use for:
775 #[stable(feature = "rust1", since = "1.0.0")]
776 fn map<B, F>(self, f: F) -> Map<Self, F>
779 F: FnMut(Self::Item) -> B,
784 /// Calls a closure on each element of an iterator.
786 /// This is equivalent to using a [`for`] loop on the iterator, although
787 /// `break` and `continue` are not possible from a closure. It's generally
788 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
789 /// when processing items at the end of longer iterator chains. In some
790 /// cases `for_each` may also be faster than a loop, because it will use
791 /// internal iteration on adapters like `Chain`.
793 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
800 /// use std::sync::mpsc::channel;
802 /// let (tx, rx) = channel();
803 /// (0..5).map(|x| x * 2 + 1)
804 /// .for_each(move |x| tx.send(x).unwrap());
806 /// let v: Vec<_> = rx.iter().collect();
807 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
810 /// For such a small example, a `for` loop may be cleaner, but `for_each`
811 /// might be preferable to keep a functional style with longer iterators:
814 /// (0..5).flat_map(|x| x * 100 .. x * 110)
816 /// .filter(|&(i, x)| (i + x) % 3 == 0)
817 /// .for_each(|(i, x)| println!("{i}:{x}"));
820 #[stable(feature = "iterator_for_each", since = "1.21.0")]
821 fn for_each<F>(self, f: F)
824 F: FnMut(Self::Item),
827 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
828 move |(), item| f(item)
831 self.fold((), call(f));
834 /// Creates an iterator which uses a closure to determine if an element
835 /// should be yielded.
837 /// Given an element the closure must return `true` or `false`. The returned
838 /// iterator will yield only the elements for which the closure returns
846 /// let a = [0i32, 1, 2];
848 /// let mut iter = a.iter().filter(|x| x.is_positive());
850 /// assert_eq!(iter.next(), Some(&1));
851 /// assert_eq!(iter.next(), Some(&2));
852 /// assert_eq!(iter.next(), None);
855 /// Because the closure passed to `filter()` takes a reference, and many
856 /// iterators iterate over references, this leads to a possibly confusing
857 /// situation, where the type of the closure is a double reference:
860 /// let a = [0, 1, 2];
862 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
864 /// assert_eq!(iter.next(), Some(&2));
865 /// assert_eq!(iter.next(), None);
868 /// It's common to instead use destructuring on the argument to strip away
872 /// let a = [0, 1, 2];
874 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
876 /// assert_eq!(iter.next(), Some(&2));
877 /// assert_eq!(iter.next(), None);
883 /// let a = [0, 1, 2];
885 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
887 /// assert_eq!(iter.next(), Some(&2));
888 /// assert_eq!(iter.next(), None);
893 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
895 #[stable(feature = "rust1", since = "1.0.0")]
896 fn filter<P>(self, predicate: P) -> Filter<Self, P>
899 P: FnMut(&Self::Item) -> bool,
901 Filter::new(self, predicate)
904 /// Creates an iterator that both filters and maps.
906 /// The returned iterator yields only the `value`s for which the supplied
907 /// closure returns `Some(value)`.
909 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
910 /// concise. The example below shows how a `map().filter().map()` can be
911 /// shortened to a single call to `filter_map`.
913 /// [`filter`]: Iterator::filter
914 /// [`map`]: Iterator::map
921 /// let a = ["1", "two", "NaN", "four", "5"];
923 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
925 /// assert_eq!(iter.next(), Some(1));
926 /// assert_eq!(iter.next(), Some(5));
927 /// assert_eq!(iter.next(), None);
930 /// Here's the same example, but with [`filter`] and [`map`]:
933 /// let a = ["1", "two", "NaN", "four", "5"];
934 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
935 /// assert_eq!(iter.next(), Some(1));
936 /// assert_eq!(iter.next(), Some(5));
937 /// assert_eq!(iter.next(), None);
940 #[stable(feature = "rust1", since = "1.0.0")]
941 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
944 F: FnMut(Self::Item) -> Option<B>,
946 FilterMap::new(self, f)
949 /// Creates an iterator which gives the current iteration count as well as
952 /// The iterator returned yields pairs `(i, val)`, where `i` is the
953 /// current index of iteration and `val` is the value returned by the
956 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
957 /// different sized integer, the [`zip`] function provides similar
960 /// # Overflow Behavior
962 /// The method does no guarding against overflows, so enumerating more than
963 /// [`usize::MAX`] elements either produces the wrong result or panics. If
964 /// debug assertions are enabled, a panic is guaranteed.
968 /// The returned iterator might panic if the to-be-returned index would
969 /// overflow a [`usize`].
971 /// [`zip`]: Iterator::zip
976 /// let a = ['a', 'b', 'c'];
978 /// let mut iter = a.iter().enumerate();
980 /// assert_eq!(iter.next(), Some((0, &'a')));
981 /// assert_eq!(iter.next(), Some((1, &'b')));
982 /// assert_eq!(iter.next(), Some((2, &'c')));
983 /// assert_eq!(iter.next(), None);
986 #[stable(feature = "rust1", since = "1.0.0")]
987 fn enumerate(self) -> Enumerate<Self>
994 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
995 /// to look at the next element of the iterator without consuming it. See
996 /// their documentation for more information.
998 /// Note that the underlying iterator is still advanced when [`peek`] or
999 /// [`peek_mut`] are called for the first time: In order to retrieve the
1000 /// next element, [`next`] is called on the underlying iterator, hence any
1001 /// side effects (i.e. anything other than fetching the next value) of
1002 /// the [`next`] method will occur.
1010 /// let xs = [1, 2, 3];
1012 /// let mut iter = xs.iter().peekable();
1014 /// // peek() lets us see into the future
1015 /// assert_eq!(iter.peek(), Some(&&1));
1016 /// assert_eq!(iter.next(), Some(&1));
1018 /// assert_eq!(iter.next(), Some(&2));
1020 /// // we can peek() multiple times, the iterator won't advance
1021 /// assert_eq!(iter.peek(), Some(&&3));
1022 /// assert_eq!(iter.peek(), Some(&&3));
1024 /// assert_eq!(iter.next(), Some(&3));
1026 /// // after the iterator is finished, so is peek()
1027 /// assert_eq!(iter.peek(), None);
1028 /// assert_eq!(iter.next(), None);
1031 /// Using [`peek_mut`] to mutate the next item without advancing the
1035 /// let xs = [1, 2, 3];
1037 /// let mut iter = xs.iter().peekable();
1039 /// // `peek_mut()` lets us see into the future
1040 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
1041 /// assert_eq!(iter.peek_mut(), Some(&mut &1));
1042 /// assert_eq!(iter.next(), Some(&1));
1044 /// if let Some(mut p) = iter.peek_mut() {
1045 /// assert_eq!(*p, &2);
1046 /// // put a value into the iterator
1050 /// // The value reappears as the iterator continues
1051 /// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
1053 /// [`peek`]: Peekable::peek
1054 /// [`peek_mut`]: Peekable::peek_mut
1055 /// [`next`]: Iterator::next
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 fn peekable(self) -> Peekable<Self>
1065 /// Creates an iterator that [`skip`]s elements based on a predicate.
1067 /// [`skip`]: Iterator::skip
1069 /// `skip_while()` takes a closure as an argument. It will call this
1070 /// closure on each element of the iterator, and ignore elements
1071 /// until it returns `false`.
1073 /// After `false` is returned, `skip_while()`'s job is over, and the
1074 /// rest of the elements are yielded.
1081 /// let a = [-1i32, 0, 1];
1083 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
1085 /// assert_eq!(iter.next(), Some(&0));
1086 /// assert_eq!(iter.next(), Some(&1));
1087 /// assert_eq!(iter.next(), None);
1090 /// Because the closure passed to `skip_while()` takes a reference, and many
1091 /// iterators iterate over references, this leads to a possibly confusing
1092 /// situation, where the type of the closure argument is a double reference:
1095 /// let a = [-1, 0, 1];
1097 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
1099 /// assert_eq!(iter.next(), Some(&0));
1100 /// assert_eq!(iter.next(), Some(&1));
1101 /// assert_eq!(iter.next(), None);
1104 /// Stopping after an initial `false`:
1107 /// let a = [-1, 0, 1, -2];
1109 /// let mut iter = a.iter().skip_while(|x| **x < 0);
1111 /// assert_eq!(iter.next(), Some(&0));
1112 /// assert_eq!(iter.next(), Some(&1));
1114 /// // while this would have been false, since we already got a false,
1115 /// // skip_while() isn't used any more
1116 /// assert_eq!(iter.next(), Some(&-2));
1118 /// assert_eq!(iter.next(), None);
1121 #[doc(alias = "drop_while")]
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1126 P: FnMut(&Self::Item) -> bool,
1128 SkipWhile::new(self, predicate)
1131 /// Creates an iterator that yields elements based on a predicate.
1133 /// `take_while()` takes a closure as an argument. It will call this
1134 /// closure on each element of the iterator, and yield elements
1135 /// while it returns `true`.
1137 /// After `false` is returned, `take_while()`'s job is over, and the
1138 /// rest of the elements are ignored.
1145 /// let a = [-1i32, 0, 1];
1147 /// let mut iter = a.iter().take_while(|x| x.is_negative());
1149 /// assert_eq!(iter.next(), Some(&-1));
1150 /// assert_eq!(iter.next(), None);
1153 /// Because the closure passed to `take_while()` takes a reference, and many
1154 /// iterators iterate over references, this leads to a possibly confusing
1155 /// situation, where the type of the closure is a double reference:
1158 /// let a = [-1, 0, 1];
1160 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
1162 /// assert_eq!(iter.next(), Some(&-1));
1163 /// assert_eq!(iter.next(), None);
1166 /// Stopping after an initial `false`:
1169 /// let a = [-1, 0, 1, -2];
1171 /// let mut iter = a.iter().take_while(|x| **x < 0);
1173 /// assert_eq!(iter.next(), Some(&-1));
1175 /// // We have more elements that are less than zero, but since we already
1176 /// // got a false, take_while() isn't used any more
1177 /// assert_eq!(iter.next(), None);
1180 /// Because `take_while()` needs to look at the value in order to see if it
1181 /// should be included or not, consuming iterators will see that it is
1185 /// let a = [1, 2, 3, 4];
1186 /// let mut iter = a.iter();
1188 /// let result: Vec<i32> = iter.by_ref()
1189 /// .take_while(|n| **n != 3)
1193 /// assert_eq!(result, &[1, 2]);
1195 /// let result: Vec<i32> = iter.cloned().collect();
1197 /// assert_eq!(result, &[4]);
1200 /// The `3` is no longer there, because it was consumed in order to see if
1201 /// the iteration should stop, but wasn't placed back into the iterator.
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1207 P: FnMut(&Self::Item) -> bool,
1209 TakeWhile::new(self, predicate)
1212 /// Creates an iterator that both yields elements based on a predicate and maps.
1214 /// `map_while()` takes a closure as an argument. It will call this
1215 /// closure on each element of the iterator, and yield elements
1216 /// while it returns [`Some(_)`][`Some`].
1223 /// let a = [-1i32, 4, 0, 1];
1225 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1227 /// assert_eq!(iter.next(), Some(-16));
1228 /// assert_eq!(iter.next(), Some(4));
1229 /// assert_eq!(iter.next(), None);
1232 /// Here's the same example, but with [`take_while`] and [`map`]:
1234 /// [`take_while`]: Iterator::take_while
1235 /// [`map`]: Iterator::map
1238 /// let a = [-1i32, 4, 0, 1];
1240 /// let mut iter = a.iter()
1241 /// .map(|x| 16i32.checked_div(*x))
1242 /// .take_while(|x| x.is_some())
1243 /// .map(|x| x.unwrap());
1245 /// assert_eq!(iter.next(), Some(-16));
1246 /// assert_eq!(iter.next(), Some(4));
1247 /// assert_eq!(iter.next(), None);
1250 /// Stopping after an initial [`None`]:
1253 /// let a = [0, 1, 2, -3, 4, 5, -6];
1255 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1256 /// let vec = iter.collect::<Vec<_>>();
1258 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1259 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1260 /// assert_eq!(vec, vec![0, 1, 2]);
1263 /// Because `map_while()` needs to look at the value in order to see if it
1264 /// should be included or not, consuming iterators will see that it is
1268 /// let a = [1, 2, -3, 4];
1269 /// let mut iter = a.iter();
1271 /// let result: Vec<u32> = iter.by_ref()
1272 /// .map_while(|n| u32::try_from(*n).ok())
1275 /// assert_eq!(result, &[1, 2]);
1277 /// let result: Vec<i32> = iter.cloned().collect();
1279 /// assert_eq!(result, &[4]);
1282 /// The `-3` is no longer there, because it was consumed in order to see if
1283 /// the iteration should stop, but wasn't placed back into the iterator.
1285 /// Note that unlike [`take_while`] this iterator is **not** fused.
1286 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1287 /// If you need fused iterator, use [`fuse`].
1289 /// [`fuse`]: Iterator::fuse
1291 #[stable(feature = "iter_map_while", since = "1.57.0")]
1292 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1295 P: FnMut(Self::Item) -> Option<B>,
1297 MapWhile::new(self, predicate)
1300 /// Creates an iterator that skips the first `n` elements.
1302 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1303 /// iterator is reached (whichever happens first). After that, all the remaining
1304 /// elements are yielded. In particular, if the original iterator is too short,
1305 /// then the returned iterator is empty.
1307 /// Rather than overriding this method directly, instead override the `nth` method.
1314 /// let a = [1, 2, 3];
1316 /// let mut iter = a.iter().skip(2);
1318 /// assert_eq!(iter.next(), Some(&3));
1319 /// assert_eq!(iter.next(), None);
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 fn skip(self, n: usize) -> Skip<Self>
1330 /// Creates an iterator that yields the first `n` elements, or fewer
1331 /// if the underlying iterator ends sooner.
1333 /// `take(n)` yields elements until `n` elements are yielded or the end of
1334 /// the iterator is reached (whichever happens first).
1335 /// The returned iterator is a prefix of length `n` if the original iterator
1336 /// contains at least `n` elements, otherwise it contains all of the
1337 /// (fewer than `n`) elements of the original iterator.
1344 /// let a = [1, 2, 3];
1346 /// let mut iter = a.iter().take(2);
1348 /// assert_eq!(iter.next(), Some(&1));
1349 /// assert_eq!(iter.next(), Some(&2));
1350 /// assert_eq!(iter.next(), None);
1353 /// `take()` is often used with an infinite iterator, to make it finite:
1356 /// let mut iter = (0..).take(3);
1358 /// assert_eq!(iter.next(), Some(0));
1359 /// assert_eq!(iter.next(), Some(1));
1360 /// assert_eq!(iter.next(), Some(2));
1361 /// assert_eq!(iter.next(), None);
1364 /// If less than `n` elements are available,
1365 /// `take` will limit itself to the size of the underlying iterator:
1369 /// let mut iter = v.into_iter().take(5);
1370 /// assert_eq!(iter.next(), Some(1));
1371 /// assert_eq!(iter.next(), Some(2));
1372 /// assert_eq!(iter.next(), None);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 fn take(self, n: usize) -> Take<Self>
1383 /// An iterator adapter similar to [`fold`] that holds internal state and
1384 /// produces a new iterator.
1386 /// [`fold`]: Iterator::fold
1388 /// `scan()` takes two arguments: an initial value which seeds the internal
1389 /// state, and a closure with two arguments, the first being a mutable
1390 /// reference to the internal state and the second an iterator element.
1391 /// The closure can assign to the internal state to share state between
1394 /// On iteration, the closure will be applied to each element of the
1395 /// iterator and the return value from the closure, an [`Option`], is
1396 /// yielded by the iterator.
1403 /// let a = [1, 2, 3];
1405 /// let mut iter = a.iter().scan(1, |state, &x| {
1406 /// // each iteration, we'll multiply the state by the element
1407 /// *state = *state * x;
1409 /// // then, we'll yield the negation of the state
1413 /// assert_eq!(iter.next(), Some(-1));
1414 /// assert_eq!(iter.next(), Some(-2));
1415 /// assert_eq!(iter.next(), Some(-6));
1416 /// assert_eq!(iter.next(), None);
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1423 F: FnMut(&mut St, Self::Item) -> Option<B>,
1425 Scan::new(self, initial_state, f)
1428 /// Creates an iterator that works like map, but flattens nested structure.
1430 /// The [`map`] adapter is very useful, but only when the closure
1431 /// argument produces values. If it produces an iterator instead, there's
1432 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1435 /// You can think of `flat_map(f)` as the semantic equivalent
1436 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1438 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1439 /// one item for each element, and `flat_map()`'s closure returns an
1440 /// iterator for each element.
1442 /// [`map`]: Iterator::map
1443 /// [`flatten`]: Iterator::flatten
1450 /// let words = ["alpha", "beta", "gamma"];
1452 /// // chars() returns an iterator
1453 /// let merged: String = words.iter()
1454 /// .flat_map(|s| s.chars())
1456 /// assert_eq!(merged, "alphabetagamma");
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1464 F: FnMut(Self::Item) -> U,
1466 FlatMap::new(self, f)
1469 /// Creates an iterator that flattens nested structure.
1471 /// This is useful when you have an iterator of iterators or an iterator of
1472 /// things that can be turned into iterators and you want to remove one
1473 /// level of indirection.
1480 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1481 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1482 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1485 /// Mapping and then flattening:
1488 /// let words = ["alpha", "beta", "gamma"];
1490 /// // chars() returns an iterator
1491 /// let merged: String = words.iter()
1492 /// .map(|s| s.chars())
1495 /// assert_eq!(merged, "alphabetagamma");
1498 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1499 /// in this case since it conveys intent more clearly:
1502 /// let words = ["alpha", "beta", "gamma"];
1504 /// // chars() returns an iterator
1505 /// let merged: String = words.iter()
1506 /// .flat_map(|s| s.chars())
1508 /// assert_eq!(merged, "alphabetagamma");
1511 /// Flattening only removes one level of nesting at a time:
1514 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1516 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1517 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1519 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1520 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1523 /// Here we see that `flatten()` does not perform a "deep" flatten.
1524 /// Instead, only one level of nesting is removed. That is, if you
1525 /// `flatten()` a three-dimensional array, the result will be
1526 /// two-dimensional and not one-dimensional. To get a one-dimensional
1527 /// structure, you have to `flatten()` again.
1529 /// [`flat_map()`]: Iterator::flat_map
1531 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1532 fn flatten(self) -> Flatten<Self>
1535 Self::Item: IntoIterator,
1540 /// Creates an iterator which ends after the first [`None`].
1542 /// After an iterator returns [`None`], future calls may or may not yield
1543 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1544 /// [`None`] is given, it will always return [`None`] forever.
1546 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1547 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1548 /// if the [`FusedIterator`] trait is improperly implemented.
1550 /// [`Some(T)`]: Some
1551 /// [`FusedIterator`]: crate::iter::FusedIterator
1558 /// // an iterator which alternates between Some and None
1559 /// struct Alternate {
1563 /// impl Iterator for Alternate {
1564 /// type Item = i32;
1566 /// fn next(&mut self) -> Option<i32> {
1567 /// let val = self.state;
1568 /// self.state = self.state + 1;
1570 /// // if it's even, Some(i32), else None
1571 /// if val % 2 == 0 {
1579 /// let mut iter = Alternate { state: 0 };
1581 /// // we can see our iterator going back and forth
1582 /// assert_eq!(iter.next(), Some(0));
1583 /// assert_eq!(iter.next(), None);
1584 /// assert_eq!(iter.next(), Some(2));
1585 /// assert_eq!(iter.next(), None);
1587 /// // however, once we fuse it...
1588 /// let mut iter = iter.fuse();
1590 /// assert_eq!(iter.next(), Some(4));
1591 /// assert_eq!(iter.next(), None);
1593 /// // it will always return `None` after the first time.
1594 /// assert_eq!(iter.next(), None);
1595 /// assert_eq!(iter.next(), None);
1596 /// assert_eq!(iter.next(), None);
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 fn fuse(self) -> Fuse<Self>
1607 /// Does something with each element of an iterator, passing the value on.
1609 /// When using iterators, you'll often chain several of them together.
1610 /// While working on such code, you might want to check out what's
1611 /// happening at various parts in the pipeline. To do that, insert
1612 /// a call to `inspect()`.
1614 /// It's more common for `inspect()` to be used as a debugging tool than to
1615 /// exist in your final code, but applications may find it useful in certain
1616 /// situations when errors need to be logged before being discarded.
1623 /// let a = [1, 4, 2, 3];
1625 /// // this iterator sequence is complex.
1626 /// let sum = a.iter()
1628 /// .filter(|x| x % 2 == 0)
1629 /// .fold(0, |sum, i| sum + i);
1631 /// println!("{sum}");
1633 /// // let's add some inspect() calls to investigate what's happening
1634 /// let sum = a.iter()
1636 /// .inspect(|x| println!("about to filter: {x}"))
1637 /// .filter(|x| x % 2 == 0)
1638 /// .inspect(|x| println!("made it through filter: {x}"))
1639 /// .fold(0, |sum, i| sum + i);
1641 /// println!("{sum}");
1644 /// This will print:
1648 /// about to filter: 1
1649 /// about to filter: 4
1650 /// made it through filter: 4
1651 /// about to filter: 2
1652 /// made it through filter: 2
1653 /// about to filter: 3
1657 /// Logging errors before discarding them:
1660 /// let lines = ["1", "2", "a"];
1662 /// let sum: i32 = lines
1664 /// .map(|line| line.parse::<i32>())
1665 /// .inspect(|num| {
1666 /// if let Err(ref e) = *num {
1667 /// println!("Parsing error: {e}");
1670 /// .filter_map(Result::ok)
1673 /// println!("Sum: {sum}");
1676 /// This will print:
1679 /// Parsing error: invalid digit found in string
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1687 F: FnMut(&Self::Item),
1689 Inspect::new(self, f)
1692 /// Borrows an iterator, rather than consuming it.
1694 /// This is useful to allow applying iterator adapters while still
1695 /// retaining ownership of the original iterator.
1702 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1704 /// // Take the first two words.
1705 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1706 /// assert_eq!(hello_world, vec!["hello", "world"]);
1708 /// // Collect the rest of the words.
1709 /// // We can only do this because we used `by_ref` earlier.
1710 /// let of_rust: Vec<_> = words.collect();
1711 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 fn by_ref(&mut self) -> &mut Self
1721 /// Transforms an iterator into a collection.
1723 /// `collect()` can take anything iterable, and turn it into a relevant
1724 /// collection. This is one of the more powerful methods in the standard
1725 /// library, used in a variety of contexts.
1727 /// The most basic pattern in which `collect()` is used is to turn one
1728 /// collection into another. You take a collection, call [`iter`] on it,
1729 /// do a bunch of transformations, and then `collect()` at the end.
1731 /// `collect()` can also create instances of types that are not typical
1732 /// collections. For example, a [`String`] can be built from [`char`]s,
1733 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1734 /// into `Result<Collection<T>, E>`. See the examples below for more.
1736 /// Because `collect()` is so general, it can cause problems with type
1737 /// inference. As such, `collect()` is one of the few times you'll see
1738 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1739 /// helps the inference algorithm understand specifically which collection
1740 /// you're trying to collect into.
1747 /// let a = [1, 2, 3];
1749 /// let doubled: Vec<i32> = a.iter()
1750 /// .map(|&x| x * 2)
1753 /// assert_eq!(vec![2, 4, 6], doubled);
1756 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1757 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1759 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1762 /// use std::collections::VecDeque;
1764 /// let a = [1, 2, 3];
1766 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1768 /// assert_eq!(2, doubled[0]);
1769 /// assert_eq!(4, doubled[1]);
1770 /// assert_eq!(6, doubled[2]);
1773 /// Using the 'turbofish' instead of annotating `doubled`:
1776 /// let a = [1, 2, 3];
1778 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1780 /// assert_eq!(vec![2, 4, 6], doubled);
1783 /// Because `collect()` only cares about what you're collecting into, you can
1784 /// still use a partial type hint, `_`, with the turbofish:
1787 /// let a = [1, 2, 3];
1789 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1791 /// assert_eq!(vec![2, 4, 6], doubled);
1794 /// Using `collect()` to make a [`String`]:
1797 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1799 /// let hello: String = chars.iter()
1800 /// .map(|&x| x as u8)
1801 /// .map(|x| (x + 1) as char)
1804 /// assert_eq!("hello", hello);
1807 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1808 /// see if any of them failed:
1811 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1813 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1815 /// // gives us the first error
1816 /// assert_eq!(Err("nope"), result);
1818 /// let results = [Ok(1), Ok(3)];
1820 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1822 /// // gives us the list of answers
1823 /// assert_eq!(Ok(vec![1, 3]), result);
1826 /// [`iter`]: Iterator::next
1827 /// [`String`]: ../../std/string/struct.String.html
1828 /// [`char`]: type@char
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1832 #[cfg_attr(not(test), rustc_diagnostic_item = "iterator_collect_fn")]
1833 fn collect<B: FromIterator<Self::Item>>(self) -> B
1837 FromIterator::from_iter(self)
1840 /// Fallibly transforms an iterator into a collection, short circuiting if
1841 /// a failure is encountered.
1843 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
1844 /// conversions during collection. Its main use case is simplifying conversions from
1845 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
1846 /// types (e.g. [`Result`]).
1848 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
1849 /// only the inner type produced on `Try::Output` must implement it. Concretely,
1850 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
1851 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
1853 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
1854 /// may continue to be used, in which case it will continue iterating starting after the element that
1855 /// triggered the failure. See the last example below for an example of how this works.
1858 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
1860 /// #![feature(iterator_try_collect)]
1862 /// let u = vec![Some(1), Some(2), Some(3)];
1863 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1864 /// assert_eq!(v, Some(vec![1, 2, 3]));
1867 /// Failing to collect in the same way:
1869 /// #![feature(iterator_try_collect)]
1871 /// let u = vec![Some(1), Some(2), None, Some(3)];
1872 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1873 /// assert_eq!(v, None);
1876 /// A similar example, but with `Result`:
1878 /// #![feature(iterator_try_collect)]
1880 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
1881 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1882 /// assert_eq!(v, Ok(vec![1, 2, 3]));
1884 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
1885 /// let v = u.into_iter().try_collect::<Vec<i32>>();
1886 /// assert_eq!(v, Err(()));
1889 /// Finally, even [`ControlFlow`] works, despite the fact that it
1890 /// doesn't implement [`FromIterator`]. Note also that the iterator can
1891 /// continue to be used, even if a failure is encountered:
1894 /// #![feature(iterator_try_collect)]
1896 /// use core::ops::ControlFlow::{Break, Continue};
1898 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
1899 /// let mut it = u.into_iter();
1901 /// let v = it.try_collect::<Vec<_>>();
1902 /// assert_eq!(v, Break(3));
1904 /// let v = it.try_collect::<Vec<_>>();
1905 /// assert_eq!(v, Continue(vec![4, 5]));
1908 /// [`collect`]: Iterator::collect
1910 #[unstable(feature = "iterator_try_collect", issue = "94047")]
1911 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
1914 <Self as Iterator>::Item: Try,
1915 <<Self as Iterator>::Item as Try>::Residual: Residual<B>,
1916 B: FromIterator<<Self::Item as Try>::Output>,
1918 try_process(ByRefSized(self), |i| i.collect())
1921 /// Collects all the items from an iterator into a collection.
1923 /// This method consumes the iterator and adds all its items to the
1924 /// passed collection. The collection is then returned, so the call chain
1925 /// can be continued.
1927 /// This is useful when you already have a collection and wants to add
1928 /// the iterator items to it.
1930 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
1931 /// but instead of being called on a collection, it's called on an iterator.
1938 /// #![feature(iter_collect_into)]
1940 /// let a = [1, 2, 3];
1941 /// let mut vec: Vec::<i32> = vec![0, 1];
1943 /// a.iter().map(|&x| x * 2).collect_into(&mut vec);
1944 /// a.iter().map(|&x| x * 10).collect_into(&mut vec);
1946 /// assert_eq!(vec![0, 1, 2, 4, 6, 10, 20, 30], vec);
1949 /// `Vec` can have a manual set capacity to avoid reallocating it:
1952 /// #![feature(iter_collect_into)]
1954 /// let a = [1, 2, 3];
1955 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
1957 /// a.iter().map(|&x| x * 2).collect_into(&mut vec);
1958 /// a.iter().map(|&x| x * 10).collect_into(&mut vec);
1960 /// assert_eq!(6, vec.capacity());
1961 /// println!("{:?}", vec);
1964 /// The returned mutable reference can be used to continue the call chain:
1967 /// #![feature(iter_collect_into)]
1969 /// let a = [1, 2, 3];
1970 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
1972 /// let count = a.iter().collect_into(&mut vec).iter().count();
1974 /// assert_eq!(count, vec.len());
1975 /// println!("Vec len is {}", count);
1977 /// let count = a.iter().collect_into(&mut vec).iter().count();
1979 /// assert_eq!(count, vec.len());
1980 /// println!("Vec len now is {}", count);
1983 #[unstable(feature = "iter_collect_into", reason = "new API", issue = "94780")]
1984 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
1988 collection.extend(self);
1992 /// Consumes an iterator, creating two collections from it.
1994 /// The predicate passed to `partition()` can return `true`, or `false`.
1995 /// `partition()` returns a pair, all of the elements for which it returned
1996 /// `true`, and all of the elements for which it returned `false`.
1998 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2000 /// [`is_partitioned()`]: Iterator::is_partitioned
2001 /// [`partition_in_place()`]: Iterator::partition_in_place
2008 /// let a = [1, 2, 3];
2010 /// let (even, odd): (Vec<_>, Vec<_>) = a
2012 /// .partition(|n| n % 2 == 0);
2014 /// assert_eq!(even, vec![2]);
2015 /// assert_eq!(odd, vec![1, 3]);
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 fn partition<B, F>(self, f: F) -> (B, B)
2021 B: Default + Extend<Self::Item>,
2022 F: FnMut(&Self::Item) -> bool,
2025 fn extend<'a, T, B: Extend<T>>(
2026 mut f: impl FnMut(&T) -> bool + 'a,
2029 ) -> impl FnMut((), T) + 'a {
2034 right.extend_one(x);
2039 let mut left: B = Default::default();
2040 let mut right: B = Default::default();
2042 self.fold((), extend(f, &mut left, &mut right));
2047 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2048 /// such that all those that return `true` precede all those that return `false`.
2049 /// Returns the number of `true` elements found.
2051 /// The relative order of partitioned items is not maintained.
2053 /// # Current implementation
2055 /// Current algorithms tries finding the first element for which the predicate evaluates
2056 /// to false, and the last element for which it evaluates to true and repeatedly swaps them.
2058 /// Time complexity: *O*(*n*)
2060 /// See also [`is_partitioned()`] and [`partition()`].
2062 /// [`is_partitioned()`]: Iterator::is_partitioned
2063 /// [`partition()`]: Iterator::partition
2068 /// #![feature(iter_partition_in_place)]
2070 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2072 /// // Partition in-place between evens and odds
2073 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
2075 /// assert_eq!(i, 3);
2076 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
2077 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
2079 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
2080 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2082 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2083 P: FnMut(&T) -> bool,
2085 // FIXME: should we worry about the count overflowing? The only way to have more than
2086 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2088 // These closure "factory" functions exist to avoid genericity in `Self`.
2092 predicate: &'a mut impl FnMut(&T) -> bool,
2093 true_count: &'a mut usize,
2094 ) -> impl FnMut(&&mut T) -> bool + 'a {
2096 let p = predicate(&**x);
2097 *true_count += p as usize;
2103 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2104 move |x| predicate(&**x)
2107 // Repeatedly find the first `false` and swap it with the last `true`.
2108 let mut true_count = 0;
2109 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2110 if let Some(tail) = self.rfind(is_true(predicate)) {
2111 crate::mem::swap(head, tail);
2120 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2121 /// such that all those that return `true` precede all those that return `false`.
2123 /// See also [`partition()`] and [`partition_in_place()`].
2125 /// [`partition()`]: Iterator::partition
2126 /// [`partition_in_place()`]: Iterator::partition_in_place
2131 /// #![feature(iter_is_partitioned)]
2133 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2134 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2136 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
2137 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2140 P: FnMut(Self::Item) -> bool,
2142 // Either all items test `true`, or the first clause stops at `false`
2143 // and we check that there are no more `true` items after that.
2144 self.all(&mut predicate) || !self.any(predicate)
2147 /// An iterator method that applies a function as long as it returns
2148 /// successfully, producing a single, final value.
2150 /// `try_fold()` takes two arguments: an initial value, and a closure with
2151 /// two arguments: an 'accumulator', and an element. The closure either
2152 /// returns successfully, with the value that the accumulator should have
2153 /// for the next iteration, or it returns failure, with an error value that
2154 /// is propagated back to the caller immediately (short-circuiting).
2156 /// The initial value is the value the accumulator will have on the first
2157 /// call. If applying the closure succeeded against every element of the
2158 /// iterator, `try_fold()` returns the final accumulator as success.
2160 /// Folding is useful whenever you have a collection of something, and want
2161 /// to produce a single value from it.
2163 /// # Note to Implementors
2165 /// Several of the other (forward) methods have default implementations in
2166 /// terms of this one, so try to implement this explicitly if it can
2167 /// do something better than the default `for` loop implementation.
2169 /// In particular, try to have this call `try_fold()` on the internal parts
2170 /// from which this iterator is composed. If multiple calls are needed,
2171 /// the `?` operator may be convenient for chaining the accumulator value
2172 /// along, but beware any invariants that need to be upheld before those
2173 /// early returns. This is a `&mut self` method, so iteration needs to be
2174 /// resumable after hitting an error here.
2181 /// let a = [1, 2, 3];
2183 /// // the checked sum of all of the elements of the array
2184 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
2186 /// assert_eq!(sum, Some(6));
2189 /// Short-circuiting:
2192 /// let a = [10, 20, 30, 100, 40, 50];
2193 /// let mut it = a.iter();
2195 /// // This sum overflows when adding the 100 element
2196 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
2197 /// assert_eq!(sum, None);
2199 /// // Because it short-circuited, the remaining elements are still
2200 /// // available through the iterator.
2201 /// assert_eq!(it.len(), 2);
2202 /// assert_eq!(it.next(), Some(&40));
2205 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2209 /// use std::ops::ControlFlow;
2211 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2212 /// if let Some(next) = prev.checked_add(x) {
2213 /// ControlFlow::Continue(next)
2215 /// ControlFlow::Break(prev)
2218 /// assert_eq!(triangular, ControlFlow::Break(120));
2220 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2221 /// if let Some(next) = prev.checked_add(x) {
2222 /// ControlFlow::Continue(next)
2224 /// ControlFlow::Break(prev)
2227 /// assert_eq!(triangular, ControlFlow::Continue(435));
2230 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2231 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2234 F: FnMut(B, Self::Item) -> R,
2237 let mut accum = init;
2238 while let Some(x) = self.next() {
2239 accum = f(accum, x)?;
2244 /// An iterator method that applies a fallible function to each item in the
2245 /// iterator, stopping at the first error and returning that error.
2247 /// This can also be thought of as the fallible form of [`for_each()`]
2248 /// or as the stateless version of [`try_fold()`].
2250 /// [`for_each()`]: Iterator::for_each
2251 /// [`try_fold()`]: Iterator::try_fold
2256 /// use std::fs::rename;
2257 /// use std::io::{stdout, Write};
2258 /// use std::path::Path;
2260 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2262 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2263 /// assert!(res.is_ok());
2265 /// let mut it = data.iter().cloned();
2266 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2267 /// assert!(res.is_err());
2268 /// // It short-circuited, so the remaining items are still in the iterator:
2269 /// assert_eq!(it.next(), Some("stale_bread.json"));
2272 /// The [`ControlFlow`] type can be used with this method for the situations
2273 /// in which you'd use `break` and `continue` in a normal loop:
2276 /// use std::ops::ControlFlow;
2278 /// let r = (2..100).try_for_each(|x| {
2279 /// if 323 % x == 0 {
2280 /// return ControlFlow::Break(x)
2283 /// ControlFlow::Continue(())
2285 /// assert_eq!(r, ControlFlow::Break(17));
2288 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2289 fn try_for_each<F, R>(&mut self, f: F) -> R
2292 F: FnMut(Self::Item) -> R,
2293 R: Try<Output = ()>,
2296 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2300 self.try_fold((), call(f))
2303 /// Folds every element into an accumulator by applying an operation,
2304 /// returning the final result.
2306 /// `fold()` takes two arguments: an initial value, and a closure with two
2307 /// arguments: an 'accumulator', and an element. The closure returns the value that
2308 /// the accumulator should have for the next iteration.
2310 /// The initial value is the value the accumulator will have on the first
2313 /// After applying this closure to every element of the iterator, `fold()`
2314 /// returns the accumulator.
2316 /// This operation is sometimes called 'reduce' or 'inject'.
2318 /// Folding is useful whenever you have a collection of something, and want
2319 /// to produce a single value from it.
2321 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2322 /// might not terminate for infinite iterators, even on traits for which a
2323 /// result is determinable in finite time.
2325 /// Note: [`reduce()`] can be used to use the first element as the initial
2326 /// value, if the accumulator type and item type is the same.
2328 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2329 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2330 /// operators like `-` the order will affect the final result.
2331 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2333 /// # Note to Implementors
2335 /// Several of the other (forward) methods have default implementations in
2336 /// terms of this one, so try to implement this explicitly if it can
2337 /// do something better than the default `for` loop implementation.
2339 /// In particular, try to have this call `fold()` on the internal parts
2340 /// from which this iterator is composed.
2347 /// let a = [1, 2, 3];
2349 /// // the sum of all of the elements of the array
2350 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2352 /// assert_eq!(sum, 6);
2355 /// Let's walk through each step of the iteration here:
2357 /// | element | acc | x | result |
2358 /// |---------|-----|---|--------|
2360 /// | 1 | 0 | 1 | 1 |
2361 /// | 2 | 1 | 2 | 3 |
2362 /// | 3 | 3 | 3 | 6 |
2364 /// And so, our final result, `6`.
2366 /// This example demonstrates the left-associative nature of `fold()`:
2367 /// it builds a string, starting with an initial value
2368 /// and continuing with each element from the front until the back:
2371 /// let numbers = [1, 2, 3, 4, 5];
2373 /// let zero = "0".to_string();
2375 /// let result = numbers.iter().fold(zero, |acc, &x| {
2376 /// format!("({acc} + {x})")
2379 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2381 /// It's common for people who haven't used iterators a lot to
2382 /// use a `for` loop with a list of things to build up a result. Those
2383 /// can be turned into `fold()`s:
2385 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2388 /// let numbers = [1, 2, 3, 4, 5];
2390 /// let mut result = 0;
2393 /// for i in &numbers {
2394 /// result = result + i;
2398 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2400 /// // they're the same
2401 /// assert_eq!(result, result2);
2404 /// [`reduce()`]: Iterator::reduce
2405 #[doc(alias = "inject", alias = "foldl")]
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2411 F: FnMut(B, Self::Item) -> B,
2413 let mut accum = init;
2414 while let Some(x) = self.next() {
2415 accum = f(accum, x);
2420 /// Reduces the elements to a single one, by repeatedly applying a reducing
2423 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2424 /// result of the reduction.
2426 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2427 /// For iterators with at least one element, this is the same as [`fold()`]
2428 /// with the first element of the iterator as the initial accumulator value, folding
2429 /// every subsequent element into it.
2431 /// [`fold()`]: Iterator::fold
2436 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
2437 /// assert_eq!(reduced, 45);
2439 /// // Which is equivalent to doing it with `fold`:
2440 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2441 /// assert_eq!(reduced, folded);
2444 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2445 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2448 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2450 let first = self.next()?;
2451 Some(self.fold(first, f))
2454 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2455 /// closure returns a failure, the failure is propagated back to the caller immediately.
2457 /// The return type of this method depends on the return type of the closure. If the closure
2458 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2459 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2460 /// `Option<Option<Self::Item>>`.
2462 /// When called on an empty iterator, this function will return either `Some(None)` or
2463 /// `Ok(None)` depending on the type of the provided closure.
2465 /// For iterators with at least one element, this is essentially the same as calling
2466 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2468 /// [`try_fold()`]: Iterator::try_fold
2472 /// Safely calculate the sum of a series of numbers:
2475 /// #![feature(iterator_try_reduce)]
2477 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2478 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2479 /// assert_eq!(sum, Some(Some(58)));
2482 /// Determine when a reduction short circuited:
2485 /// #![feature(iterator_try_reduce)]
2487 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2488 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2489 /// assert_eq!(sum, None);
2492 /// Determine when a reduction was not performed because there are no elements:
2495 /// #![feature(iterator_try_reduce)]
2497 /// let numbers: Vec<usize> = Vec::new();
2498 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2499 /// assert_eq!(sum, Some(None));
2502 /// Use a [`Result`] instead of an [`Option`]:
2505 /// #![feature(iterator_try_reduce)]
2507 /// let numbers = vec!["1", "2", "3", "4", "5"];
2508 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2509 /// numbers.into_iter().try_reduce(|x, y| {
2510 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2512 /// assert_eq!(max, Ok(Some("5")));
2515 #[unstable(feature = "iterator_try_reduce", reason = "new API", issue = "87053")]
2516 fn try_reduce<F, R>(&mut self, f: F) -> ChangeOutputType<R, Option<R::Output>>
2519 F: FnMut(Self::Item, Self::Item) -> R,
2520 R: Try<Output = Self::Item>,
2521 R::Residual: Residual<Option<Self::Item>>,
2523 let first = match self.next() {
2525 None => return Try::from_output(None),
2528 match self.try_fold(first, f).branch() {
2529 ControlFlow::Break(r) => FromResidual::from_residual(r),
2530 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2534 /// Tests if every element of the iterator matches a predicate.
2536 /// `all()` takes a closure that returns `true` or `false`. It applies
2537 /// this closure to each element of the iterator, and if they all return
2538 /// `true`, then so does `all()`. If any of them return `false`, it
2539 /// returns `false`.
2541 /// `all()` is short-circuiting; in other words, it will stop processing
2542 /// as soon as it finds a `false`, given that no matter what else happens,
2543 /// the result will also be `false`.
2545 /// An empty iterator returns `true`.
2552 /// let a = [1, 2, 3];
2554 /// assert!(a.iter().all(|&x| x > 0));
2556 /// assert!(!a.iter().all(|&x| x > 2));
2559 /// Stopping at the first `false`:
2562 /// let a = [1, 2, 3];
2564 /// let mut iter = a.iter();
2566 /// assert!(!iter.all(|&x| x != 2));
2568 /// // we can still use `iter`, as there are more elements.
2569 /// assert_eq!(iter.next(), Some(&3));
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 fn all<F>(&mut self, f: F) -> bool
2576 F: FnMut(Self::Item) -> bool,
2579 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2581 if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
2584 self.try_fold((), check(f)) == ControlFlow::CONTINUE
2587 /// Tests if any element of the iterator matches a predicate.
2589 /// `any()` takes a closure that returns `true` or `false`. It applies
2590 /// this closure to each element of the iterator, and if any of them return
2591 /// `true`, then so does `any()`. If they all return `false`, it
2592 /// returns `false`.
2594 /// `any()` is short-circuiting; in other words, it will stop processing
2595 /// as soon as it finds a `true`, given that no matter what else happens,
2596 /// the result will also be `true`.
2598 /// An empty iterator returns `false`.
2605 /// let a = [1, 2, 3];
2607 /// assert!(a.iter().any(|&x| x > 0));
2609 /// assert!(!a.iter().any(|&x| x > 5));
2612 /// Stopping at the first `true`:
2615 /// let a = [1, 2, 3];
2617 /// let mut iter = a.iter();
2619 /// assert!(iter.any(|&x| x != 2));
2621 /// // we can still use `iter`, as there are more elements.
2622 /// assert_eq!(iter.next(), Some(&2));
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 fn any<F>(&mut self, f: F) -> bool
2629 F: FnMut(Self::Item) -> bool,
2632 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2634 if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
2638 self.try_fold((), check(f)) == ControlFlow::BREAK
2641 /// Searches for an element of an iterator that satisfies a predicate.
2643 /// `find()` takes a closure that returns `true` or `false`. It applies
2644 /// this closure to each element of the iterator, and if any of them return
2645 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2646 /// `false`, it returns [`None`].
2648 /// `find()` is short-circuiting; in other words, it will stop processing
2649 /// as soon as the closure returns `true`.
2651 /// Because `find()` takes a reference, and many iterators iterate over
2652 /// references, this leads to a possibly confusing situation where the
2653 /// argument is a double reference. You can see this effect in the
2654 /// examples below, with `&&x`.
2656 /// [`Some(element)`]: Some
2663 /// let a = [1, 2, 3];
2665 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2667 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2670 /// Stopping at the first `true`:
2673 /// let a = [1, 2, 3];
2675 /// let mut iter = a.iter();
2677 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2679 /// // we can still use `iter`, as there are more elements.
2680 /// assert_eq!(iter.next(), Some(&3));
2683 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2685 #[stable(feature = "rust1", since = "1.0.0")]
2686 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2689 P: FnMut(&Self::Item) -> bool,
2692 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2694 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
2698 self.try_fold((), check(predicate)).break_value()
2701 /// Applies function to the elements of iterator and returns
2702 /// the first non-none result.
2704 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2709 /// let a = ["lol", "NaN", "2", "5"];
2711 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2713 /// assert_eq!(first_number, Some(2));
2716 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2717 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2720 F: FnMut(Self::Item) -> Option<B>,
2723 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2724 move |(), x| match f(x) {
2725 Some(x) => ControlFlow::Break(x),
2726 None => ControlFlow::CONTINUE,
2730 self.try_fold((), check(f)).break_value()
2733 /// Applies function to the elements of iterator and returns
2734 /// the first true result or the first error.
2736 /// The return type of this method depends on the return type of the closure.
2737 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
2738 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
2743 /// #![feature(try_find)]
2745 /// let a = ["1", "2", "lol", "NaN", "5"];
2747 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2748 /// Ok(s.parse::<i32>()? == search)
2751 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2752 /// assert_eq!(result, Ok(Some(&"2")));
2754 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2755 /// assert!(result.is_err());
2758 /// This also supports other types which implement `Try`, not just `Result`.
2760 /// #![feature(try_find)]
2762 /// use std::num::NonZeroU32;
2763 /// let a = [3, 5, 7, 4, 9, 0, 11];
2764 /// let result = a.iter().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2765 /// assert_eq!(result, Some(Some(&4)));
2766 /// let result = a.iter().take(3).try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2767 /// assert_eq!(result, Some(None));
2768 /// let result = a.iter().rev().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2769 /// assert_eq!(result, None);
2772 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2773 fn try_find<F, R>(&mut self, f: F) -> ChangeOutputType<R, Option<Self::Item>>
2776 F: FnMut(&Self::Item) -> R,
2777 R: Try<Output = bool>,
2778 R::Residual: Residual<Option<Self::Item>>,
2782 mut f: impl FnMut(&I) -> V,
2783 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
2785 V: Try<Output = bool, Residual = R>,
2786 R: Residual<Option<I>>,
2788 move |(), x| match f(&x).branch() {
2789 ControlFlow::Continue(false) => ControlFlow::CONTINUE,
2790 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
2791 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
2795 match self.try_fold((), check(f)) {
2796 ControlFlow::Break(x) => x,
2797 ControlFlow::Continue(()) => Try::from_output(None),
2801 /// Searches for an element in an iterator, returning its index.
2803 /// `position()` takes a closure that returns `true` or `false`. It applies
2804 /// this closure to each element of the iterator, and if one of them
2805 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2806 /// them return `false`, it returns [`None`].
2808 /// `position()` is short-circuiting; in other words, it will stop
2809 /// processing as soon as it finds a `true`.
2811 /// # Overflow Behavior
2813 /// The method does no guarding against overflows, so if there are more
2814 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2815 /// result or panics. If debug assertions are enabled, a panic is
2820 /// This function might panic if the iterator has more than `usize::MAX`
2821 /// non-matching elements.
2823 /// [`Some(index)`]: Some
2830 /// let a = [1, 2, 3];
2832 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2834 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2837 /// Stopping at the first `true`:
2840 /// let a = [1, 2, 3, 4];
2842 /// let mut iter = a.iter();
2844 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2846 /// // we can still use `iter`, as there are more elements.
2847 /// assert_eq!(iter.next(), Some(&3));
2849 /// // The returned index depends on iterator state
2850 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 fn position<P>(&mut self, predicate: P) -> Option<usize>
2858 P: FnMut(Self::Item) -> bool,
2862 mut predicate: impl FnMut(T) -> bool,
2863 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2864 #[rustc_inherit_overflow_checks]
2866 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
2870 self.try_fold(0, check(predicate)).break_value()
2873 /// Searches for an element in an iterator from the right, returning its
2876 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2877 /// this closure to each element of the iterator, starting from the end,
2878 /// and if one of them returns `true`, then `rposition()` returns
2879 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2881 /// `rposition()` is short-circuiting; in other words, it will stop
2882 /// processing as soon as it finds a `true`.
2884 /// [`Some(index)`]: Some
2891 /// let a = [1, 2, 3];
2893 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2895 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2898 /// Stopping at the first `true`:
2901 /// let a = [-1, 2, 3, 4];
2903 /// let mut iter = a.iter();
2905 /// assert_eq!(iter.rposition(|&x| x >= 2), Some(3));
2907 /// // we can still use `iter`, as there are more elements.
2908 /// assert_eq!(iter.next(), Some(&-1));
2911 #[stable(feature = "rust1", since = "1.0.0")]
2912 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2914 P: FnMut(Self::Item) -> bool,
2915 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2917 // No need for an overflow check here, because `ExactSizeIterator`
2918 // implies that the number of elements fits into a `usize`.
2921 mut predicate: impl FnMut(T) -> bool,
2922 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
2925 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
2930 self.try_rfold(n, check(predicate)).break_value()
2933 /// Returns the maximum element of an iterator.
2935 /// If several elements are equally maximum, the last element is
2936 /// returned. If the iterator is empty, [`None`] is returned.
2938 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2939 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2942 /// [2.4, f32::NAN, 1.3]
2944 /// .reduce(f32::max)
2955 /// let a = [1, 2, 3];
2956 /// let b: Vec<u32> = Vec::new();
2958 /// assert_eq!(a.iter().max(), Some(&3));
2959 /// assert_eq!(b.iter().max(), None);
2962 #[stable(feature = "rust1", since = "1.0.0")]
2963 fn max(self) -> Option<Self::Item>
2968 self.max_by(Ord::cmp)
2971 /// Returns the minimum element of an iterator.
2973 /// If several elements are equally minimum, the first element is returned.
2974 /// If the iterator is empty, [`None`] is returned.
2976 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
2977 /// incomparable. You can work around this by using [`Iterator::reduce`]:
2980 /// [2.4, f32::NAN, 1.3]
2982 /// .reduce(f32::min)
2993 /// let a = [1, 2, 3];
2994 /// let b: Vec<u32> = Vec::new();
2996 /// assert_eq!(a.iter().min(), Some(&1));
2997 /// assert_eq!(b.iter().min(), None);
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 fn min(self) -> Option<Self::Item>
3006 self.min_by(Ord::cmp)
3009 /// Returns the element that gives the maximum value from the
3010 /// specified function.
3012 /// If several elements are equally maximum, the last element is
3013 /// returned. If the iterator is empty, [`None`] is returned.
3018 /// let a = [-3_i32, 0, 1, 5, -10];
3019 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
3022 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3023 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3026 F: FnMut(&Self::Item) -> B,
3029 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3034 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3038 let (_, x) = self.map(key(f)).max_by(compare)?;
3042 /// Returns the element that gives the maximum value with respect to the
3043 /// specified comparison function.
3045 /// If several elements are equally maximum, the last element is
3046 /// returned. If the iterator is empty, [`None`] is returned.
3051 /// let a = [-3_i32, 0, 1, 5, -10];
3052 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3055 #[stable(feature = "iter_max_by", since = "1.15.0")]
3056 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3059 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3062 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3063 move |x, y| cmp::max_by(x, y, &mut compare)
3066 self.reduce(fold(compare))
3069 /// Returns the element that gives the minimum value from the
3070 /// specified function.
3072 /// If several elements are equally minimum, the first element is
3073 /// returned. If the iterator is empty, [`None`] is returned.
3078 /// let a = [-3_i32, 0, 1, 5, -10];
3079 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
3082 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3083 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3086 F: FnMut(&Self::Item) -> B,
3089 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3094 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3098 let (_, x) = self.map(key(f)).min_by(compare)?;
3102 /// Returns the element that gives the minimum value with respect to the
3103 /// specified comparison function.
3105 /// If several elements are equally minimum, the first element is
3106 /// returned. If the iterator is empty, [`None`] is returned.
3111 /// let a = [-3_i32, 0, 1, 5, -10];
3112 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3115 #[stable(feature = "iter_min_by", since = "1.15.0")]
3116 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3119 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3122 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3123 move |x, y| cmp::min_by(x, y, &mut compare)
3126 self.reduce(fold(compare))
3129 /// Reverses an iterator's direction.
3131 /// Usually, iterators iterate from left to right. After using `rev()`,
3132 /// an iterator will instead iterate from right to left.
3134 /// This is only possible if the iterator has an end, so `rev()` only
3135 /// works on [`DoubleEndedIterator`]s.
3140 /// let a = [1, 2, 3];
3142 /// let mut iter = a.iter().rev();
3144 /// assert_eq!(iter.next(), Some(&3));
3145 /// assert_eq!(iter.next(), Some(&2));
3146 /// assert_eq!(iter.next(), Some(&1));
3148 /// assert_eq!(iter.next(), None);
3151 #[doc(alias = "reverse")]
3152 #[stable(feature = "rust1", since = "1.0.0")]
3153 fn rev(self) -> Rev<Self>
3155 Self: Sized + DoubleEndedIterator,
3160 /// Converts an iterator of pairs into a pair of containers.
3162 /// `unzip()` consumes an entire iterator of pairs, producing two
3163 /// collections: one from the left elements of the pairs, and one
3164 /// from the right elements.
3166 /// This function is, in some sense, the opposite of [`zip`].
3168 /// [`zip`]: Iterator::zip
3175 /// let a = [(1, 2), (3, 4), (5, 6)];
3177 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
3179 /// assert_eq!(left, [1, 3, 5]);
3180 /// assert_eq!(right, [2, 4, 6]);
3182 /// // you can also unzip multiple nested tuples at once
3183 /// let a = [(1, (2, 3)), (4, (5, 6))];
3185 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.iter().cloned().unzip();
3186 /// assert_eq!(x, [1, 4]);
3187 /// assert_eq!(y, [2, 5]);
3188 /// assert_eq!(z, [3, 6]);
3190 #[stable(feature = "rust1", since = "1.0.0")]
3191 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3193 FromA: Default + Extend<A>,
3194 FromB: Default + Extend<B>,
3195 Self: Sized + Iterator<Item = (A, B)>,
3197 let mut unzipped: (FromA, FromB) = Default::default();
3198 unzipped.extend(self);
3202 /// Creates an iterator which copies all of its elements.
3204 /// This is useful when you have an iterator over `&T`, but you need an
3205 /// iterator over `T`.
3212 /// let a = [1, 2, 3];
3214 /// let v_copied: Vec<_> = a.iter().copied().collect();
3216 /// // copied is the same as .map(|&x| x)
3217 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3219 /// assert_eq!(v_copied, vec![1, 2, 3]);
3220 /// assert_eq!(v_map, vec![1, 2, 3]);
3222 #[stable(feature = "iter_copied", since = "1.36.0")]
3223 fn copied<'a, T: 'a>(self) -> Copied<Self>
3225 Self: Sized + Iterator<Item = &'a T>,
3231 /// Creates an iterator which [`clone`]s all of its elements.
3233 /// This is useful when you have an iterator over `&T`, but you need an
3234 /// iterator over `T`.
3236 /// There is no guarantee whatsoever about the `clone` method actually
3237 /// being called *or* optimized away. So code should not depend on
3240 /// [`clone`]: Clone::clone
3247 /// let a = [1, 2, 3];
3249 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3251 /// // cloned is the same as .map(|&x| x), for integers
3252 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3254 /// assert_eq!(v_cloned, vec![1, 2, 3]);
3255 /// assert_eq!(v_map, vec![1, 2, 3]);
3258 /// To get the best performance, try to clone late:
3261 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3262 /// // don't do this:
3263 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3264 /// assert_eq!(&[vec![23]], &slower[..]);
3265 /// // instead call `cloned` late
3266 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3267 /// assert_eq!(&[vec![23]], &faster[..]);
3269 #[stable(feature = "rust1", since = "1.0.0")]
3270 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
3272 Self: Sized + Iterator<Item = &'a T>,
3278 /// Repeats an iterator endlessly.
3280 /// Instead of stopping at [`None`], the iterator will instead start again,
3281 /// from the beginning. After iterating again, it will start at the
3282 /// beginning again. And again. And again. Forever. Note that in case the
3283 /// original iterator is empty, the resulting iterator will also be empty.
3290 /// let a = [1, 2, 3];
3292 /// let mut it = a.iter().cycle();
3294 /// assert_eq!(it.next(), Some(&1));
3295 /// assert_eq!(it.next(), Some(&2));
3296 /// assert_eq!(it.next(), Some(&3));
3297 /// assert_eq!(it.next(), Some(&1));
3298 /// assert_eq!(it.next(), Some(&2));
3299 /// assert_eq!(it.next(), Some(&3));
3300 /// assert_eq!(it.next(), Some(&1));
3302 #[stable(feature = "rust1", since = "1.0.0")]
3304 fn cycle(self) -> Cycle<Self>
3306 Self: Sized + Clone,
3311 /// Returns an iterator over `N` elements of the iterator at a time.
3313 /// The chunks do not overlap. If `N` does not divide the length of the
3314 /// iterator, then the last up to `N-1` elements will be omitted and can be
3315 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3316 /// function of the iterator.
3320 /// Panics if `N` is 0.
3327 /// #![feature(iter_array_chunks)]
3329 /// let mut iter = "lorem".chars().array_chunks();
3330 /// assert_eq!(iter.next(), Some(['l', 'o']));
3331 /// assert_eq!(iter.next(), Some(['r', 'e']));
3332 /// assert_eq!(iter.next(), None);
3333 /// assert_eq!(iter.into_remainder().unwrap().as_slice(), &['m']);
3337 /// #![feature(iter_array_chunks)]
3339 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3340 /// // ^-----^ ^------^
3341 /// for [x, y, z] in data.iter().array_chunks() {
3342 /// assert_eq!(x + y + z, 4);
3346 #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
3347 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3351 ArrayChunks::new(self)
3354 /// Sums the elements of an iterator.
3356 /// Takes each element, adds them together, and returns the result.
3358 /// An empty iterator returns the zero value of the type.
3362 /// When calling `sum()` and a primitive integer type is being returned, this
3363 /// method will panic if the computation overflows and debug assertions are
3371 /// let a = [1, 2, 3];
3372 /// let sum: i32 = a.iter().sum();
3374 /// assert_eq!(sum, 6);
3376 #[stable(feature = "iter_arith", since = "1.11.0")]
3377 fn sum<S>(self) -> S
3385 /// Iterates over the entire iterator, multiplying all the elements
3387 /// An empty iterator returns the one value of the type.
3391 /// When calling `product()` and a primitive integer type is being returned,
3392 /// method will panic if the computation overflows and debug assertions are
3398 /// fn factorial(n: u32) -> u32 {
3399 /// (1..=n).product()
3401 /// assert_eq!(factorial(0), 1);
3402 /// assert_eq!(factorial(1), 1);
3403 /// assert_eq!(factorial(5), 120);
3405 #[stable(feature = "iter_arith", since = "1.11.0")]
3406 fn product<P>(self) -> P
3409 P: Product<Self::Item>,
3411 Product::product(self)
3414 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3420 /// use std::cmp::Ordering;
3422 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3423 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3424 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3426 #[stable(feature = "iter_order", since = "1.5.0")]
3427 fn cmp<I>(self, other: I) -> Ordering
3429 I: IntoIterator<Item = Self::Item>,
3433 self.cmp_by(other, |x, y| x.cmp(&y))
3436 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3437 /// of another with respect to the specified comparison function.
3444 /// #![feature(iter_order_by)]
3446 /// use std::cmp::Ordering;
3448 /// let xs = [1, 2, 3, 4];
3449 /// let ys = [1, 4, 9, 16];
3451 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
3452 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
3453 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
3455 #[unstable(feature = "iter_order_by", issue = "64295")]
3456 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3460 F: FnMut(Self::Item, I::Item) -> Ordering,
3463 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3465 F: FnMut(X, Y) -> Ordering,
3467 move |x, y| match cmp(x, y) {
3468 Ordering::Equal => ControlFlow::CONTINUE,
3469 non_eq => ControlFlow::Break(non_eq),
3473 match iter_compare(self, other.into_iter(), compare(cmp)) {
3474 ControlFlow::Continue(ord) => ord,
3475 ControlFlow::Break(ord) => ord,
3479 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3485 /// use std::cmp::Ordering;
3487 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3488 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3489 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3491 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3493 #[stable(feature = "iter_order", since = "1.5.0")]
3494 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3497 Self::Item: PartialOrd<I::Item>,
3500 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3503 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3504 /// of another with respect to the specified comparison function.
3511 /// #![feature(iter_order_by)]
3513 /// use std::cmp::Ordering;
3515 /// let xs = [1.0, 2.0, 3.0, 4.0];
3516 /// let ys = [1.0, 4.0, 9.0, 16.0];
3519 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
3520 /// Some(Ordering::Less)
3523 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
3524 /// Some(Ordering::Equal)
3527 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
3528 /// Some(Ordering::Greater)
3531 #[unstable(feature = "iter_order_by", issue = "64295")]
3532 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3536 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3539 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3541 F: FnMut(X, Y) -> Option<Ordering>,
3543 move |x, y| match partial_cmp(x, y) {
3544 Some(Ordering::Equal) => ControlFlow::CONTINUE,
3545 non_eq => ControlFlow::Break(non_eq),
3549 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3550 ControlFlow::Continue(ord) => Some(ord),
3551 ControlFlow::Break(ord) => ord,
3555 /// Determines if the elements of this [`Iterator`] are equal to those of
3561 /// assert_eq!([1].iter().eq([1].iter()), true);
3562 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3564 #[stable(feature = "iter_order", since = "1.5.0")]
3565 fn eq<I>(self, other: I) -> bool
3568 Self::Item: PartialEq<I::Item>,
3571 self.eq_by(other, |x, y| x == y)
3574 /// Determines if the elements of this [`Iterator`] are equal to those of
3575 /// another with respect to the specified equality function.
3582 /// #![feature(iter_order_by)]
3584 /// let xs = [1, 2, 3, 4];
3585 /// let ys = [1, 4, 9, 16];
3587 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3589 #[unstable(feature = "iter_order_by", issue = "64295")]
3590 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3594 F: FnMut(Self::Item, I::Item) -> bool,
3597 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3599 F: FnMut(X, Y) -> bool,
3602 if eq(x, y) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
3606 match iter_compare(self, other.into_iter(), compare(eq)) {
3607 ControlFlow::Continue(ord) => ord == Ordering::Equal,
3608 ControlFlow::Break(()) => false,
3612 /// Determines if the elements of this [`Iterator`] are unequal to those of
3618 /// assert_eq!([1].iter().ne([1].iter()), false);
3619 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3621 #[stable(feature = "iter_order", since = "1.5.0")]
3622 fn ne<I>(self, other: I) -> bool
3625 Self::Item: PartialEq<I::Item>,
3631 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3632 /// less than those of another.
3637 /// assert_eq!([1].iter().lt([1].iter()), false);
3638 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3639 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3640 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3642 #[stable(feature = "iter_order", since = "1.5.0")]
3643 fn lt<I>(self, other: I) -> bool
3646 Self::Item: PartialOrd<I::Item>,
3649 self.partial_cmp(other) == Some(Ordering::Less)
3652 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3653 /// less or equal to those of another.
3658 /// assert_eq!([1].iter().le([1].iter()), true);
3659 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3660 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3661 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3663 #[stable(feature = "iter_order", since = "1.5.0")]
3664 fn le<I>(self, other: I) -> bool
3667 Self::Item: PartialOrd<I::Item>,
3670 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3673 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3674 /// greater than those of another.
3679 /// assert_eq!([1].iter().gt([1].iter()), false);
3680 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3681 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3682 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3684 #[stable(feature = "iter_order", since = "1.5.0")]
3685 fn gt<I>(self, other: I) -> bool
3688 Self::Item: PartialOrd<I::Item>,
3691 self.partial_cmp(other) == Some(Ordering::Greater)
3694 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3695 /// greater than or equal to those of another.
3700 /// assert_eq!([1].iter().ge([1].iter()), true);
3701 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3702 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3703 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3705 #[stable(feature = "iter_order", since = "1.5.0")]
3706 fn ge<I>(self, other: I) -> bool
3709 Self::Item: PartialOrd<I::Item>,
3712 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3715 /// Checks if the elements of this iterator are sorted.
3717 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3718 /// iterator yields exactly zero or one element, `true` is returned.
3720 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3721 /// implies that this function returns `false` if any two consecutive items are not
3727 /// #![feature(is_sorted)]
3729 /// assert!([1, 2, 2, 9].iter().is_sorted());
3730 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3731 /// assert!([0].iter().is_sorted());
3732 /// assert!(std::iter::empty::<i32>().is_sorted());
3733 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3736 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3737 fn is_sorted(self) -> bool
3740 Self::Item: PartialOrd,
3742 self.is_sorted_by(PartialOrd::partial_cmp)
3745 /// Checks if the elements of this iterator are sorted using the given comparator function.
3747 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3748 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3749 /// [`is_sorted`]; see its documentation for more information.
3754 /// #![feature(is_sorted)]
3756 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3757 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3758 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3759 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3760 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3763 /// [`is_sorted`]: Iterator::is_sorted
3764 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3765 fn is_sorted_by<F>(mut self, compare: F) -> bool
3768 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3773 mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
3774 ) -> impl FnMut(T) -> bool + 'a {
3776 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3784 let mut last = match self.next() {
3786 None => return true,
3789 self.all(check(&mut last, compare))
3792 /// Checks if the elements of this iterator are sorted using the given key extraction
3795 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3796 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3797 /// its documentation for more information.
3799 /// [`is_sorted`]: Iterator::is_sorted
3804 /// #![feature(is_sorted)]
3806 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3807 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3810 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3811 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3814 F: FnMut(Self::Item) -> K,
3817 self.map(f).is_sorted()
3820 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
3821 // The unusual name is to avoid name collisions in method resolution
3825 #[unstable(feature = "trusted_random_access", issue = "none")]
3826 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
3828 Self: TrustedRandomAccessNoCoerce,
3830 unreachable!("Always specialized");
3834 /// Compares two iterators element-wise using the given function.
3836 /// If `ControlFlow::CONTINUE` is returned from the function, the comparison moves on to the next
3837 /// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
3838 /// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
3839 /// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
3842 /// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
3843 /// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
3845 fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
3849 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
3852 fn compare<'a, B, X, T>(
3854 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
3855 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
3859 move |x| match b.next() {
3860 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
3861 Some(y) => f(x, y).map_break(ControlFlow::Break),
3865 match a.try_for_each(compare(&mut b, f)) {
3866 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
3867 None => Ordering::Equal,
3868 Some(_) => Ordering::Less,
3870 ControlFlow::Break(x) => x,
3874 #[stable(feature = "rust1", since = "1.0.0")]
3875 impl<I: Iterator + ?Sized> Iterator for &mut I {
3876 type Item = I::Item;
3878 fn next(&mut self) -> Option<I::Item> {
3881 fn size_hint(&self) -> (usize, Option<usize>) {
3882 (**self).size_hint()
3884 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
3885 (**self).advance_by(n)
3887 fn nth(&mut self, n: usize) -> Option<Self::Item> {