1 // ignore-tidy-filelength
2 // This file almost exclusively consists of the definition of `Iterator`. We
3 // can't split that into multiple files.
5 use crate::cmp::{self, Ordering};
6 use crate::ops::{Add, Try};
8 use super::super::LoopState;
9 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
10 use super::super::{FlatMap, Flatten};
11 use super::super::{FromIterator, Product, Sum, Zip};
13 Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
16 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
18 /// An interface for dealing with iterators.
20 /// This is the main iterator trait. For more about the concept of iterators
21 /// generally, please see the [module-level documentation]. In particular, you
22 /// may want to know how to [implement `Iterator`][impl].
24 /// [module-level documentation]: index.html
25 /// [impl]: index.html#implementing-iterator
26 #[stable(feature = "rust1", since = "1.0.0")]
27 #[rustc_on_unimplemented(
29 _Self = "[std::ops::Range<Idx>; 1]",
30 label = "if you meant to iterate between two values, remove the square brackets",
31 note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
32 without the brackets: `start..end`"
35 _Self = "[std::ops::RangeFrom<Idx>; 1]",
36 label = "if you meant to iterate from a value onwards, remove the square brackets",
37 note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
38 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
39 unbounded iterator will run forever unless you `break` or `return` from within the \
43 _Self = "[std::ops::RangeTo<Idx>; 1]",
44 label = "if you meant to iterate until a value, remove the square brackets and add a \
46 note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
47 `Range` without the brackets: `0..end`"
50 _Self = "[std::ops::RangeInclusive<Idx>; 1]",
51 label = "if you meant to iterate between two values, remove the square brackets",
52 note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
53 `RangeInclusive` without the brackets: `start..=end`"
56 _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
57 label = "if you meant to iterate until a value (including it), remove the square brackets \
58 and add a starting value",
59 note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
60 bounded `RangeInclusive` without the brackets: `0..=end`"
63 _Self = "std::ops::RangeTo<Idx>",
64 label = "if you meant to iterate until a value, add a starting value",
65 note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
66 bounded `Range`: `0..end`"
69 _Self = "std::ops::RangeToInclusive<Idx>",
70 label = "if you meant to iterate until a value (including it), add a starting value",
71 note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
72 to have a bounded `RangeInclusive`: `0..=end`"
76 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
79 _Self = "std::string::String",
80 label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 label = "borrow the array with `&` or call `.iter()` on it to iterate over it",
85 note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
89 note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
90 syntax `start..end` or the inclusive range syntax `start..=end`"
92 label = "`{Self}` is not an iterator",
93 message = "`{Self}` is not an iterator"
96 #[must_use = "iterators are lazy and do nothing unless consumed"]
98 /// The type of the elements being iterated over.
99 #[stable(feature = "rust1", since = "1.0.0")]
102 /// Advances the iterator and returns the next value.
104 /// Returns [`None`] when iteration is finished. Individual iterator
105 /// implementations may choose to resume iteration, and so calling `next()`
106 /// again may or may not eventually start returning [`Some(Item)`] again at some
109 /// [`None`]: ../../std/option/enum.Option.html#variant.None
110 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
117 /// let a = [1, 2, 3];
119 /// let mut iter = a.iter();
121 /// // A call to next() returns the next value...
122 /// assert_eq!(Some(&1), iter.next());
123 /// assert_eq!(Some(&2), iter.next());
124 /// assert_eq!(Some(&3), iter.next());
126 /// // ... and then None once it's over.
127 /// assert_eq!(None, iter.next());
129 /// // More calls may or may not return `None`. Here, they always will.
130 /// assert_eq!(None, iter.next());
131 /// assert_eq!(None, iter.next());
133 #[stable(feature = "rust1", since = "1.0.0")]
134 fn next(&mut self) -> Option<Self::Item>;
136 /// Returns the bounds on the remaining length of the iterator.
138 /// Specifically, `size_hint()` returns a tuple where the first element
139 /// is the lower bound, and the second element is the upper bound.
141 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
142 /// A [`None`] here means that either there is no known upper bound, or the
143 /// upper bound is larger than [`usize`].
145 /// # Implementation notes
147 /// It is not enforced that an iterator implementation yields the declared
148 /// number of elements. A buggy iterator may yield less than the lower bound
149 /// or more than the upper bound of elements.
151 /// `size_hint()` is primarily intended to be used for optimizations such as
152 /// reserving space for the elements of the iterator, but must not be
153 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
154 /// implementation of `size_hint()` should not lead to memory safety
157 /// That said, the implementation should provide a correct estimation,
158 /// because otherwise it would be a violation of the trait's protocol.
160 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
163 /// [`usize`]: ../../std/primitive.usize.html
164 /// [`Option`]: ../../std/option/enum.Option.html
165 /// [`None`]: ../../std/option/enum.Option.html#variant.None
172 /// let a = [1, 2, 3];
173 /// let iter = a.iter();
175 /// assert_eq!((3, Some(3)), iter.size_hint());
178 /// A more complex example:
181 /// // The even numbers from zero to ten.
182 /// let iter = (0..10).filter(|x| x % 2 == 0);
184 /// // We might iterate from zero to ten times. Knowing that it's five
185 /// // exactly wouldn't be possible without executing filter().
186 /// assert_eq!((0, Some(10)), iter.size_hint());
188 /// // Let's add five more numbers with chain()
189 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
191 /// // now both bounds are increased by five
192 /// assert_eq!((5, Some(15)), iter.size_hint());
195 /// Returning `None` for an upper bound:
198 /// // an infinite iterator has no upper bound
199 /// // and the maximum possible lower bound
202 /// assert_eq!((usize::MAX, None), iter.size_hint());
205 #[stable(feature = "rust1", since = "1.0.0")]
206 fn size_hint(&self) -> (usize, Option<usize>) {
210 /// Consumes the iterator, counting the number of iterations and returning it.
212 /// This method will call [`next`] repeatedly until [`None`] is encountered,
213 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
214 /// called at least once even if the iterator does not have any elements.
216 /// [`next`]: #tymethod.next
217 /// [`None`]: ../../std/option/enum.Option.html#variant.None
218 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
220 /// # Overflow Behavior
222 /// The method does no guarding against overflows, so counting elements of
223 /// an iterator with more than [`usize::MAX`] elements either produces the
224 /// wrong result or panics. If debug assertions are enabled, a panic is
229 /// This function might panic if the iterator has more than [`usize::MAX`]
232 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
239 /// let a = [1, 2, 3];
240 /// assert_eq!(a.iter().count(), 3);
242 /// let a = [1, 2, 3, 4, 5];
243 /// assert_eq!(a.iter().count(), 5);
246 #[stable(feature = "rust1", since = "1.0.0")]
247 fn count(self) -> usize
252 fn add1<T>(count: usize, _: T) -> usize {
260 /// Consumes the iterator, returning the last element.
262 /// This method will evaluate the iterator until it returns [`None`]. While
263 /// doing so, it keeps track of the current element. After [`None`] is
264 /// returned, `last()` will then return the last element it saw.
266 /// [`None`]: ../../std/option/enum.Option.html#variant.None
273 /// let a = [1, 2, 3];
274 /// assert_eq!(a.iter().last(), Some(&3));
276 /// let a = [1, 2, 3, 4, 5];
277 /// assert_eq!(a.iter().last(), Some(&5));
280 #[stable(feature = "rust1", since = "1.0.0")]
281 fn last(self) -> Option<Self::Item>
286 fn some<T>(_: Option<T>, x: T) -> Option<T> {
290 self.fold(None, some)
293 /// Returns the `n`th element of the iterator.
295 /// Like most indexing operations, the count starts from zero, so `nth(0)`
296 /// returns the first value, `nth(1)` the second, and so on.
298 /// Note that all preceding elements, as well as the returned element, will be
299 /// consumed from the iterator. That means that the preceding elements will be
300 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
301 /// will return different elements.
303 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
306 /// [`None`]: ../../std/option/enum.Option.html#variant.None
313 /// let a = [1, 2, 3];
314 /// assert_eq!(a.iter().nth(1), Some(&2));
317 /// Calling `nth()` multiple times doesn't rewind the iterator:
320 /// let a = [1, 2, 3];
322 /// let mut iter = a.iter();
324 /// assert_eq!(iter.nth(1), Some(&2));
325 /// assert_eq!(iter.nth(1), None);
328 /// Returning `None` if there are less than `n + 1` elements:
331 /// let a = [1, 2, 3];
332 /// assert_eq!(a.iter().nth(10), None);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
337 while let Some(x) = self.next() {
346 /// Creates an iterator starting at the same point, but stepping by
347 /// the given amount at each iteration.
349 /// Note 1: The first element of the iterator will always be returned,
350 /// regardless of the step given.
352 /// Note 2: The time at which ignored elements are pulled is not fixed.
353 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
354 /// but is also free to behave like the sequence
355 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
356 /// Which way is used may change for some iterators for performance reasons.
357 /// The second way will advance the iterator earlier and may consume more items.
359 /// `advance_n_and_return_first` is the equivalent of:
361 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
365 /// let next = iter.next();
366 /// if total_step > 1 {
367 /// iter.nth(total_step-2);
375 /// The method will panic if the given step is `0`.
382 /// let a = [0, 1, 2, 3, 4, 5];
383 /// let mut iter = a.iter().step_by(2);
385 /// assert_eq!(iter.next(), Some(&0));
386 /// assert_eq!(iter.next(), Some(&2));
387 /// assert_eq!(iter.next(), Some(&4));
388 /// assert_eq!(iter.next(), None);
391 #[stable(feature = "iterator_step_by", since = "1.28.0")]
392 fn step_by(self, step: usize) -> StepBy<Self>
396 StepBy::new(self, step)
399 /// Takes two iterators and creates a new iterator over both in sequence.
401 /// `chain()` will return a new iterator which will first iterate over
402 /// values from the first iterator and then over values from the second
405 /// In other words, it links two iterators together, in a chain. 🔗
407 /// [`once`] is commonly used to adapt a single value into a chain of
408 /// other kinds of iteration.
415 /// let a1 = [1, 2, 3];
416 /// let a2 = [4, 5, 6];
418 /// let mut iter = a1.iter().chain(a2.iter());
420 /// assert_eq!(iter.next(), Some(&1));
421 /// assert_eq!(iter.next(), Some(&2));
422 /// assert_eq!(iter.next(), Some(&3));
423 /// assert_eq!(iter.next(), Some(&4));
424 /// assert_eq!(iter.next(), Some(&5));
425 /// assert_eq!(iter.next(), Some(&6));
426 /// assert_eq!(iter.next(), None);
429 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
430 /// anything that can be converted into an [`Iterator`], not just an
431 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
432 /// [`IntoIterator`], and so can be passed to `chain()` directly:
435 /// let s1 = &[1, 2, 3];
436 /// let s2 = &[4, 5, 6];
438 /// let mut iter = s1.iter().chain(s2);
440 /// assert_eq!(iter.next(), Some(&1));
441 /// assert_eq!(iter.next(), Some(&2));
442 /// assert_eq!(iter.next(), Some(&3));
443 /// assert_eq!(iter.next(), Some(&4));
444 /// assert_eq!(iter.next(), Some(&5));
445 /// assert_eq!(iter.next(), Some(&6));
446 /// assert_eq!(iter.next(), None);
449 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
453 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
454 /// use std::os::windows::ffi::OsStrExt;
455 /// s.encode_wide().chain(std::iter::once(0)).collect()
459 /// [`once`]: fn.once.html
460 /// [`Iterator`]: trait.Iterator.html
461 /// [`IntoIterator`]: trait.IntoIterator.html
462 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
464 #[stable(feature = "rust1", since = "1.0.0")]
465 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
468 U: IntoIterator<Item = Self::Item>,
470 Chain::new(self, other.into_iter())
473 /// 'Zips up' two iterators into a single iterator of pairs.
475 /// `zip()` returns a new iterator that will iterate over two other
476 /// iterators, returning a tuple where the first element comes from the
477 /// first iterator, and the second element comes from the second iterator.
479 /// In other words, it zips two iterators together, into a single one.
481 /// If either iterator returns [`None`], [`next`] from the zipped iterator
482 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
483 /// short-circuit and `next` will not be called on the second iterator.
490 /// let a1 = [1, 2, 3];
491 /// let a2 = [4, 5, 6];
493 /// let mut iter = a1.iter().zip(a2.iter());
495 /// assert_eq!(iter.next(), Some((&1, &4)));
496 /// assert_eq!(iter.next(), Some((&2, &5)));
497 /// assert_eq!(iter.next(), Some((&3, &6)));
498 /// assert_eq!(iter.next(), None);
501 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
502 /// anything that can be converted into an [`Iterator`], not just an
503 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
504 /// [`IntoIterator`], and so can be passed to `zip()` directly:
506 /// [`IntoIterator`]: trait.IntoIterator.html
507 /// [`Iterator`]: trait.Iterator.html
510 /// let s1 = &[1, 2, 3];
511 /// let s2 = &[4, 5, 6];
513 /// let mut iter = s1.iter().zip(s2);
515 /// assert_eq!(iter.next(), Some((&1, &4)));
516 /// assert_eq!(iter.next(), Some((&2, &5)));
517 /// assert_eq!(iter.next(), Some((&3, &6)));
518 /// assert_eq!(iter.next(), None);
521 /// `zip()` is often used to zip an infinite iterator to a finite one.
522 /// This works because the finite iterator will eventually return [`None`],
523 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
526 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
528 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
530 /// assert_eq!((0, 'f'), enumerate[0]);
531 /// assert_eq!((0, 'f'), zipper[0]);
533 /// assert_eq!((1, 'o'), enumerate[1]);
534 /// assert_eq!((1, 'o'), zipper[1]);
536 /// assert_eq!((2, 'o'), enumerate[2]);
537 /// assert_eq!((2, 'o'), zipper[2]);
540 /// [`enumerate`]: trait.Iterator.html#method.enumerate
541 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
542 /// [`None`]: ../../std/option/enum.Option.html#variant.None
544 #[stable(feature = "rust1", since = "1.0.0")]
545 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
550 Zip::new(self, other.into_iter())
553 /// Takes a closure and creates an iterator which calls that closure on each
556 /// `map()` transforms one iterator into another, by means of its argument:
557 /// something that implements [`FnMut`]. It produces a new iterator which
558 /// calls this closure on each element of the original iterator.
560 /// If you are good at thinking in types, you can think of `map()` like this:
561 /// If you have an iterator that gives you elements of some type `A`, and
562 /// you want an iterator of some other type `B`, you can use `map()`,
563 /// passing a closure that takes an `A` and returns a `B`.
565 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
566 /// lazy, it is best used when you're already working with other iterators.
567 /// If you're doing some sort of looping for a side effect, it's considered
568 /// more idiomatic to use [`for`] than `map()`.
570 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
571 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
578 /// let a = [1, 2, 3];
580 /// let mut iter = a.iter().map(|x| 2 * x);
582 /// assert_eq!(iter.next(), Some(2));
583 /// assert_eq!(iter.next(), Some(4));
584 /// assert_eq!(iter.next(), Some(6));
585 /// assert_eq!(iter.next(), None);
588 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
591 /// # #![allow(unused_must_use)]
592 /// // don't do this:
593 /// (0..5).map(|x| println!("{}", x));
595 /// // it won't even execute, as it is lazy. Rust will warn you about this.
597 /// // Instead, use for:
599 /// println!("{}", x);
603 #[stable(feature = "rust1", since = "1.0.0")]
604 fn map<B, F>(self, f: F) -> Map<Self, F>
607 F: FnMut(Self::Item) -> B,
612 /// Calls a closure on each element of an iterator.
614 /// This is equivalent to using a [`for`] loop on the iterator, although
615 /// `break` and `continue` are not possible from a closure. It's generally
616 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
617 /// when processing items at the end of longer iterator chains. In some
618 /// cases `for_each` may also be faster than a loop, because it will use
619 /// internal iteration on adaptors like `Chain`.
621 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
628 /// use std::sync::mpsc::channel;
630 /// let (tx, rx) = channel();
631 /// (0..5).map(|x| x * 2 + 1)
632 /// .for_each(move |x| tx.send(x).unwrap());
634 /// let v: Vec<_> = rx.iter().collect();
635 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
638 /// For such a small example, a `for` loop may be cleaner, but `for_each`
639 /// might be preferable to keep a functional style with longer iterators:
642 /// (0..5).flat_map(|x| x * 100 .. x * 110)
644 /// .filter(|&(i, x)| (i + x) % 3 == 0)
645 /// .for_each(|(i, x)| println!("{}:{}", i, x));
648 #[stable(feature = "iterator_for_each", since = "1.21.0")]
649 fn for_each<F>(self, f: F)
652 F: FnMut(Self::Item),
655 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
656 move |(), item| f(item)
659 self.fold((), call(f));
662 /// Creates an iterator which uses a closure to determine if an element
663 /// should be yielded.
665 /// The closure must return `true` or `false`. `filter()` creates an
666 /// iterator which calls this closure on each element. If the closure
667 /// returns `true`, then the element is returned. If the closure returns
668 /// `false`, it will try again, and call the closure on the next element,
669 /// seeing if it passes the test.
676 /// let a = [0i32, 1, 2];
678 /// let mut iter = a.iter().filter(|x| x.is_positive());
680 /// assert_eq!(iter.next(), Some(&1));
681 /// assert_eq!(iter.next(), Some(&2));
682 /// assert_eq!(iter.next(), None);
685 /// Because the closure passed to `filter()` takes a reference, and many
686 /// iterators iterate over references, this leads to a possibly confusing
687 /// situation, where the type of the closure is a double reference:
690 /// let a = [0, 1, 2];
692 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
694 /// assert_eq!(iter.next(), Some(&2));
695 /// assert_eq!(iter.next(), None);
698 /// It's common to instead use destructuring on the argument to strip away
702 /// let a = [0, 1, 2];
704 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
706 /// assert_eq!(iter.next(), Some(&2));
707 /// assert_eq!(iter.next(), None);
713 /// let a = [0, 1, 2];
715 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
717 /// assert_eq!(iter.next(), Some(&2));
718 /// assert_eq!(iter.next(), None);
723 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn filter<P>(self, predicate: P) -> Filter<Self, P>
729 P: FnMut(&Self::Item) -> bool,
731 Filter::new(self, predicate)
734 /// Creates an iterator that both filters and maps.
736 /// The closure must return an [`Option<T>`]. `filter_map` creates an
737 /// iterator which calls this closure on each element. If the closure
738 /// returns [`Some(element)`][`Some`], then that element is returned. If the
739 /// closure returns [`None`], it will try again, and call the closure on the
740 /// next element, seeing if it will return [`Some`].
742 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
745 /// [`filter`]: #method.filter
746 /// [`map`]: #method.map
748 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
750 /// In other words, it removes the [`Option<T>`] layer automatically. If your
751 /// mapping is already returning an [`Option<T>`] and you want to skip over
752 /// [`None`]s, then `filter_map` is much, much nicer to use.
759 /// let a = ["1", "lol", "3", "NaN", "5"];
761 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
763 /// assert_eq!(iter.next(), Some(1));
764 /// assert_eq!(iter.next(), Some(3));
765 /// assert_eq!(iter.next(), Some(5));
766 /// assert_eq!(iter.next(), None);
769 /// Here's the same example, but with [`filter`] and [`map`]:
772 /// let a = ["1", "lol", "3", "NaN", "5"];
773 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
774 /// assert_eq!(iter.next(), Some(1));
775 /// assert_eq!(iter.next(), Some(3));
776 /// assert_eq!(iter.next(), Some(5));
777 /// assert_eq!(iter.next(), None);
780 /// [`Option<T>`]: ../../std/option/enum.Option.html
781 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
782 /// [`None`]: ../../std/option/enum.Option.html#variant.None
784 #[stable(feature = "rust1", since = "1.0.0")]
785 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
788 F: FnMut(Self::Item) -> Option<B>,
790 FilterMap::new(self, f)
793 /// Creates an iterator which gives the current iteration count as well as
796 /// The iterator returned yields pairs `(i, val)`, where `i` is the
797 /// current index of iteration and `val` is the value returned by the
800 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
801 /// different sized integer, the [`zip`] function provides similar
804 /// # Overflow Behavior
806 /// The method does no guarding against overflows, so enumerating more than
807 /// [`usize::MAX`] elements either produces the wrong result or panics. If
808 /// debug assertions are enabled, a panic is guaranteed.
812 /// The returned iterator might panic if the to-be-returned index would
813 /// overflow a [`usize`].
815 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
816 /// [`usize`]: ../../std/primitive.usize.html
817 /// [`zip`]: #method.zip
822 /// let a = ['a', 'b', 'c'];
824 /// let mut iter = a.iter().enumerate();
826 /// assert_eq!(iter.next(), Some((0, &'a')));
827 /// assert_eq!(iter.next(), Some((1, &'b')));
828 /// assert_eq!(iter.next(), Some((2, &'c')));
829 /// assert_eq!(iter.next(), None);
832 #[stable(feature = "rust1", since = "1.0.0")]
833 fn enumerate(self) -> Enumerate<Self>
840 /// Creates an iterator which can use `peek` to look at the next element of
841 /// the iterator without consuming it.
843 /// Adds a [`peek`] method to an iterator. See its documentation for
844 /// more information.
846 /// Note that the underlying iterator is still advanced when [`peek`] is
847 /// called for the first time: In order to retrieve the next element,
848 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
849 /// anything other than fetching the next value) of the [`next`] method
852 /// [`peek`]: struct.Peekable.html#method.peek
853 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
860 /// let xs = [1, 2, 3];
862 /// let mut iter = xs.iter().peekable();
864 /// // peek() lets us see into the future
865 /// assert_eq!(iter.peek(), Some(&&1));
866 /// assert_eq!(iter.next(), Some(&1));
868 /// assert_eq!(iter.next(), Some(&2));
870 /// // we can peek() multiple times, the iterator won't advance
871 /// assert_eq!(iter.peek(), Some(&&3));
872 /// assert_eq!(iter.peek(), Some(&&3));
874 /// assert_eq!(iter.next(), Some(&3));
876 /// // after the iterator is finished, so is peek()
877 /// assert_eq!(iter.peek(), None);
878 /// assert_eq!(iter.next(), None);
881 #[stable(feature = "rust1", since = "1.0.0")]
882 fn peekable(self) -> Peekable<Self>
889 /// Creates an iterator that [`skip`]s elements based on a predicate.
891 /// [`skip`]: #method.skip
893 /// `skip_while()` takes a closure as an argument. It will call this
894 /// closure on each element of the iterator, and ignore elements
895 /// until it returns `false`.
897 /// After `false` is returned, `skip_while()`'s job is over, and the
898 /// rest of the elements are yielded.
905 /// let a = [-1i32, 0, 1];
907 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
909 /// assert_eq!(iter.next(), Some(&0));
910 /// assert_eq!(iter.next(), Some(&1));
911 /// assert_eq!(iter.next(), None);
914 /// Because the closure passed to `skip_while()` takes a reference, and many
915 /// iterators iterate over references, this leads to a possibly confusing
916 /// situation, where the type of the closure is a double reference:
919 /// let a = [-1, 0, 1];
921 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
923 /// assert_eq!(iter.next(), Some(&0));
924 /// assert_eq!(iter.next(), Some(&1));
925 /// assert_eq!(iter.next(), None);
928 /// Stopping after an initial `false`:
931 /// let a = [-1, 0, 1, -2];
933 /// let mut iter = a.iter().skip_while(|x| **x < 0);
935 /// assert_eq!(iter.next(), Some(&0));
936 /// assert_eq!(iter.next(), Some(&1));
938 /// // while this would have been false, since we already got a false,
939 /// // skip_while() isn't used any more
940 /// assert_eq!(iter.next(), Some(&-2));
942 /// assert_eq!(iter.next(), None);
945 #[stable(feature = "rust1", since = "1.0.0")]
946 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
949 P: FnMut(&Self::Item) -> bool,
951 SkipWhile::new(self, predicate)
954 /// Creates an iterator that yields elements based on a predicate.
956 /// `take_while()` takes a closure as an argument. It will call this
957 /// closure on each element of the iterator, and yield elements
958 /// while it returns `true`.
960 /// After `false` is returned, `take_while()`'s job is over, and the
961 /// rest of the elements are ignored.
968 /// let a = [-1i32, 0, 1];
970 /// let mut iter = a.iter().take_while(|x| x.is_negative());
972 /// assert_eq!(iter.next(), Some(&-1));
973 /// assert_eq!(iter.next(), None);
976 /// Because the closure passed to `take_while()` takes a reference, and many
977 /// iterators iterate over references, this leads to a possibly confusing
978 /// situation, where the type of the closure is a double reference:
981 /// let a = [-1, 0, 1];
983 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
985 /// assert_eq!(iter.next(), Some(&-1));
986 /// assert_eq!(iter.next(), None);
989 /// Stopping after an initial `false`:
992 /// let a = [-1, 0, 1, -2];
994 /// let mut iter = a.iter().take_while(|x| **x < 0);
996 /// assert_eq!(iter.next(), Some(&-1));
998 /// // We have more elements that are less than zero, but since we already
999 /// // got a false, take_while() isn't used any more
1000 /// assert_eq!(iter.next(), None);
1003 /// Because `take_while()` needs to look at the value in order to see if it
1004 /// should be included or not, consuming iterators will see that it is
1008 /// let a = [1, 2, 3, 4];
1009 /// let mut iter = a.iter();
1011 /// let result: Vec<i32> = iter.by_ref()
1012 /// .take_while(|n| **n != 3)
1016 /// assert_eq!(result, &[1, 2]);
1018 /// let result: Vec<i32> = iter.cloned().collect();
1020 /// assert_eq!(result, &[4]);
1023 /// The `3` is no longer there, because it was consumed in order to see if
1024 /// the iteration should stop, but wasn't placed back into the iterator.
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1030 P: FnMut(&Self::Item) -> bool,
1032 TakeWhile::new(self, predicate)
1035 /// Creates an iterator that both yields elements based on a predicate and maps.
1037 /// `map_while()` takes a closure as an argument. It will call this
1038 /// closure on each element of the iterator, and yield elements
1039 /// while it returns [`Some(_)`][`Some`].
1046 /// #![feature(iter_map_while)]
1047 /// let a = [-1i32, 4, 0, 1];
1049 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1051 /// assert_eq!(iter.next(), Some(-16));
1052 /// assert_eq!(iter.next(), Some(4));
1053 /// assert_eq!(iter.next(), None);
1056 /// Here's the same example, but with [`take_while`] and [`map`]:
1058 /// [`take_while`]: #method.take_while
1059 /// [`map`]: #method.map
1062 /// let a = [-1i32, 4, 0, 1];
1064 /// let mut iter = a.iter()
1065 /// .map(|x| 16i32.checked_div(*x))
1066 /// .take_while(|x| x.is_some())
1067 /// .map(|x| x.unwrap());
1069 /// assert_eq!(iter.next(), Some(-16));
1070 /// assert_eq!(iter.next(), Some(4));
1071 /// assert_eq!(iter.next(), None);
1074 /// Stopping after an initial [`None`]:
1077 /// #![feature(iter_map_while)]
1078 /// use std::convert::TryFrom;
1080 /// let a = [0, 1, 2, -3, 4, 5, -6];
1082 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1083 /// let vec = iter.collect::<Vec<_>>();
1085 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1086 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` entcountered.
1087 /// assert_eq!(vec, vec![0, 1, 2]);
1090 /// Because `map_while()` needs to look at the value in order to see if it
1091 /// should be included or not, consuming iterators will see that it is
1095 /// #![feature(iter_map_while)]
1096 /// use std::convert::TryFrom;
1098 /// let a = [1, 2, -3, 4];
1099 /// let mut iter = a.iter();
1101 /// let result: Vec<u32> = iter.by_ref()
1102 /// .map_while(|n| u32::try_from(*n).ok())
1105 /// assert_eq!(result, &[1, 2]);
1107 /// let result: Vec<i32> = iter.cloned().collect();
1109 /// assert_eq!(result, &[4]);
1112 /// The `-3` is no longer there, because it was consumed in order to see if
1113 /// the iteration should stop, but wasn't placed back into the iterator.
1115 /// Note that unlike [`take_while`] this iterator is **not** fused.
1116 /// It is also not specified what this iterator returns after the first` None` is returned.
1117 /// If you need fused iterator, use [`fuse`].
1119 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
1120 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1121 /// [`fuse`]: #method.fuse
1123 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1124 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1127 P: FnMut(Self::Item) -> Option<B>,
1129 MapWhile::new(self, predicate)
1132 /// Creates an iterator that skips the first `n` elements.
1134 /// After they have been consumed, the rest of the elements are yielded.
1135 /// Rather than overriding this method directly, instead override the `nth` method.
1142 /// let a = [1, 2, 3];
1144 /// let mut iter = a.iter().skip(2);
1146 /// assert_eq!(iter.next(), Some(&3));
1147 /// assert_eq!(iter.next(), None);
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 fn skip(self, n: usize) -> Skip<Self>
1158 /// Creates an iterator that yields its first `n` elements.
1165 /// let a = [1, 2, 3];
1167 /// let mut iter = a.iter().take(2);
1169 /// assert_eq!(iter.next(), Some(&1));
1170 /// assert_eq!(iter.next(), Some(&2));
1171 /// assert_eq!(iter.next(), None);
1174 /// `take()` is often used with an infinite iterator, to make it finite:
1177 /// let mut iter = (0..).take(3);
1179 /// assert_eq!(iter.next(), Some(0));
1180 /// assert_eq!(iter.next(), Some(1));
1181 /// assert_eq!(iter.next(), Some(2));
1182 /// assert_eq!(iter.next(), None);
1185 /// If less than `n` elements are available,
1186 /// `take` will limit itself to the size of the underlying iterator:
1189 /// let v = vec![1, 2];
1190 /// let mut iter = v.into_iter().take(5);
1191 /// assert_eq!(iter.next(), Some(1));
1192 /// assert_eq!(iter.next(), Some(2));
1193 /// assert_eq!(iter.next(), None);
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 fn take(self, n: usize) -> Take<Self>
1204 /// An iterator adaptor similar to [`fold`] that holds internal state and
1205 /// produces a new iterator.
1207 /// [`fold`]: #method.fold
1209 /// `scan()` takes two arguments: an initial value which seeds the internal
1210 /// state, and a closure with two arguments, the first being a mutable
1211 /// reference to the internal state and the second an iterator element.
1212 /// The closure can assign to the internal state to share state between
1215 /// On iteration, the closure will be applied to each element of the
1216 /// iterator and the return value from the closure, an [`Option`], is
1217 /// yielded by the iterator.
1219 /// [`Option`]: ../../std/option/enum.Option.html
1226 /// let a = [1, 2, 3];
1228 /// let mut iter = a.iter().scan(1, |state, &x| {
1229 /// // each iteration, we'll multiply the state by the element
1230 /// *state = *state * x;
1232 /// // then, we'll yield the negation of the state
1236 /// assert_eq!(iter.next(), Some(-1));
1237 /// assert_eq!(iter.next(), Some(-2));
1238 /// assert_eq!(iter.next(), Some(-6));
1239 /// assert_eq!(iter.next(), None);
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1246 F: FnMut(&mut St, Self::Item) -> Option<B>,
1248 Scan::new(self, initial_state, f)
1251 /// Creates an iterator that works like map, but flattens nested structure.
1253 /// The [`map`] adapter is very useful, but only when the closure
1254 /// argument produces values. If it produces an iterator instead, there's
1255 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1258 /// You can think of `flat_map(f)` as the semantic equivalent
1259 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1261 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1262 /// one item for each element, and `flat_map()`'s closure returns an
1263 /// iterator for each element.
1265 /// [`map`]: #method.map
1266 /// [`flatten`]: #method.flatten
1273 /// let words = ["alpha", "beta", "gamma"];
1275 /// // chars() returns an iterator
1276 /// let merged: String = words.iter()
1277 /// .flat_map(|s| s.chars())
1279 /// assert_eq!(merged, "alphabetagamma");
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1287 F: FnMut(Self::Item) -> U,
1289 FlatMap::new(self, f)
1292 /// Creates an iterator that flattens nested structure.
1294 /// This is useful when you have an iterator of iterators or an iterator of
1295 /// things that can be turned into iterators and you want to remove one
1296 /// level of indirection.
1303 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1304 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1305 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1308 /// Mapping and then flattening:
1311 /// let words = ["alpha", "beta", "gamma"];
1313 /// // chars() returns an iterator
1314 /// let merged: String = words.iter()
1315 /// .map(|s| s.chars())
1318 /// assert_eq!(merged, "alphabetagamma");
1321 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1322 /// in this case since it conveys intent more clearly:
1325 /// let words = ["alpha", "beta", "gamma"];
1327 /// // chars() returns an iterator
1328 /// let merged: String = words.iter()
1329 /// .flat_map(|s| s.chars())
1331 /// assert_eq!(merged, "alphabetagamma");
1334 /// Flattening once only removes one level of nesting:
1337 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1339 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1340 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1342 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1343 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1346 /// Here we see that `flatten()` does not perform a "deep" flatten.
1347 /// Instead, only one level of nesting is removed. That is, if you
1348 /// `flatten()` a three-dimensional array the result will be
1349 /// two-dimensional and not one-dimensional. To get a one-dimensional
1350 /// structure, you have to `flatten()` again.
1352 /// [`flat_map()`]: #method.flat_map
1354 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1355 fn flatten(self) -> Flatten<Self>
1358 Self::Item: IntoIterator,
1363 /// Creates an iterator which ends after the first [`None`].
1365 /// After an iterator returns [`None`], future calls may or may not yield
1366 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1367 /// [`None`] is given, it will always return [`None`] forever.
1369 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1370 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1377 /// // an iterator which alternates between Some and None
1378 /// struct Alternate {
1382 /// impl Iterator for Alternate {
1383 /// type Item = i32;
1385 /// fn next(&mut self) -> Option<i32> {
1386 /// let val = self.state;
1387 /// self.state = self.state + 1;
1389 /// // if it's even, Some(i32), else None
1390 /// if val % 2 == 0 {
1398 /// let mut iter = Alternate { state: 0 };
1400 /// // we can see our iterator going back and forth
1401 /// assert_eq!(iter.next(), Some(0));
1402 /// assert_eq!(iter.next(), None);
1403 /// assert_eq!(iter.next(), Some(2));
1404 /// assert_eq!(iter.next(), None);
1406 /// // however, once we fuse it...
1407 /// let mut iter = iter.fuse();
1409 /// assert_eq!(iter.next(), Some(4));
1410 /// assert_eq!(iter.next(), None);
1412 /// // it will always return `None` after the first time.
1413 /// assert_eq!(iter.next(), None);
1414 /// assert_eq!(iter.next(), None);
1415 /// assert_eq!(iter.next(), None);
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 fn fuse(self) -> Fuse<Self>
1426 /// Does something with each element of an iterator, passing the value on.
1428 /// When using iterators, you'll often chain several of them together.
1429 /// While working on such code, you might want to check out what's
1430 /// happening at various parts in the pipeline. To do that, insert
1431 /// a call to `inspect()`.
1433 /// It's more common for `inspect()` to be used as a debugging tool than to
1434 /// exist in your final code, but applications may find it useful in certain
1435 /// situations when errors need to be logged before being discarded.
1442 /// let a = [1, 4, 2, 3];
1444 /// // this iterator sequence is complex.
1445 /// let sum = a.iter()
1447 /// .filter(|x| x % 2 == 0)
1448 /// .fold(0, |sum, i| sum + i);
1450 /// println!("{}", sum);
1452 /// // let's add some inspect() calls to investigate what's happening
1453 /// let sum = a.iter()
1455 /// .inspect(|x| println!("about to filter: {}", x))
1456 /// .filter(|x| x % 2 == 0)
1457 /// .inspect(|x| println!("made it through filter: {}", x))
1458 /// .fold(0, |sum, i| sum + i);
1460 /// println!("{}", sum);
1463 /// This will print:
1467 /// about to filter: 1
1468 /// about to filter: 4
1469 /// made it through filter: 4
1470 /// about to filter: 2
1471 /// made it through filter: 2
1472 /// about to filter: 3
1476 /// Logging errors before discarding them:
1479 /// let lines = ["1", "2", "a"];
1481 /// let sum: i32 = lines
1483 /// .map(|line| line.parse::<i32>())
1484 /// .inspect(|num| {
1485 /// if let Err(ref e) = *num {
1486 /// println!("Parsing error: {}", e);
1489 /// .filter_map(Result::ok)
1492 /// println!("Sum: {}", sum);
1495 /// This will print:
1498 /// Parsing error: invalid digit found in string
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1506 F: FnMut(&Self::Item),
1508 Inspect::new(self, f)
1511 /// Borrows an iterator, rather than consuming it.
1513 /// This is useful to allow applying iterator adaptors while still
1514 /// retaining ownership of the original iterator.
1521 /// let a = [1, 2, 3];
1523 /// let iter = a.iter();
1525 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1527 /// assert_eq!(sum, 6);
1529 /// // if we try to use iter again, it won't work. The following line
1530 /// // gives "error: use of moved value: `iter`
1531 /// // assert_eq!(iter.next(), None);
1533 /// // let's try that again
1534 /// let a = [1, 2, 3];
1536 /// let mut iter = a.iter();
1538 /// // instead, we add in a .by_ref()
1539 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1541 /// assert_eq!(sum, 3);
1543 /// // now this is just fine:
1544 /// assert_eq!(iter.next(), Some(&3));
1545 /// assert_eq!(iter.next(), None);
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 fn by_ref(&mut self) -> &mut Self
1555 /// Transforms an iterator into a collection.
1557 /// `collect()` can take anything iterable, and turn it into a relevant
1558 /// collection. This is one of the more powerful methods in the standard
1559 /// library, used in a variety of contexts.
1561 /// The most basic pattern in which `collect()` is used is to turn one
1562 /// collection into another. You take a collection, call [`iter`] on it,
1563 /// do a bunch of transformations, and then `collect()` at the end.
1565 /// One of the keys to `collect()`'s power is that many things you might
1566 /// not think of as 'collections' actually are. For example, a [`String`]
1567 /// is a collection of [`char`]s. And a collection of
1568 /// [`Result<T, E>`][`Result`] can be thought of as single
1569 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1571 /// Because `collect()` is so general, it can cause problems with type
1572 /// inference. As such, `collect()` is one of the few times you'll see
1573 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1574 /// helps the inference algorithm understand specifically which collection
1575 /// you're trying to collect into.
1582 /// let a = [1, 2, 3];
1584 /// let doubled: Vec<i32> = a.iter()
1585 /// .map(|&x| x * 2)
1588 /// assert_eq!(vec![2, 4, 6], doubled);
1591 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1592 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1594 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1597 /// use std::collections::VecDeque;
1599 /// let a = [1, 2, 3];
1601 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1603 /// assert_eq!(2, doubled[0]);
1604 /// assert_eq!(4, doubled[1]);
1605 /// assert_eq!(6, doubled[2]);
1608 /// Using the 'turbofish' instead of annotating `doubled`:
1611 /// let a = [1, 2, 3];
1613 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1615 /// assert_eq!(vec![2, 4, 6], doubled);
1618 /// Because `collect()` only cares about what you're collecting into, you can
1619 /// still use a partial type hint, `_`, with the turbofish:
1622 /// let a = [1, 2, 3];
1624 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1626 /// assert_eq!(vec![2, 4, 6], doubled);
1629 /// Using `collect()` to make a [`String`]:
1632 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1634 /// let hello: String = chars.iter()
1635 /// .map(|&x| x as u8)
1636 /// .map(|x| (x + 1) as char)
1639 /// assert_eq!("hello", hello);
1642 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1643 /// see if any of them failed:
1646 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1648 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1650 /// // gives us the first error
1651 /// assert_eq!(Err("nope"), result);
1653 /// let results = [Ok(1), Ok(3)];
1655 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1657 /// // gives us the list of answers
1658 /// assert_eq!(Ok(vec![1, 3]), result);
1661 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1662 /// [`String`]: ../../std/string/struct.String.html
1663 /// [`char`]: ../../std/primitive.char.html
1664 /// [`Result`]: ../../std/result/enum.Result.html
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1668 fn collect<B: FromIterator<Self::Item>>(self) -> B
1672 FromIterator::from_iter(self)
1675 /// Consumes an iterator, creating two collections from it.
1677 /// The predicate passed to `partition()` can return `true`, or `false`.
1678 /// `partition()` returns a pair, all of the elements for which it returned
1679 /// `true`, and all of the elements for which it returned `false`.
1681 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1683 /// [`is_partitioned()`]: #method.is_partitioned
1684 /// [`partition_in_place()`]: #method.partition_in_place
1691 /// let a = [1, 2, 3];
1693 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1695 /// .partition(|&n| n % 2 == 0);
1697 /// assert_eq!(even, vec![2]);
1698 /// assert_eq!(odd, vec![1, 3]);
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 fn partition<B, F>(self, f: F) -> (B, B)
1704 B: Default + Extend<Self::Item>,
1705 F: FnMut(&Self::Item) -> bool,
1708 fn extend<'a, T, B: Extend<T>>(
1709 mut f: impl FnMut(&T) -> bool + 'a,
1712 ) -> impl FnMut((), T) + 'a {
1717 right.extend_one(x);
1722 let mut left: B = Default::default();
1723 let mut right: B = Default::default();
1725 self.fold((), extend(f, &mut left, &mut right));
1730 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1731 /// such that all those that return `true` precede all those that return `false`.
1732 /// Returns the number of `true` elements found.
1734 /// The relative order of partitioned items is not maintained.
1736 /// See also [`is_partitioned()`] and [`partition()`].
1738 /// [`is_partitioned()`]: #method.is_partitioned
1739 /// [`partition()`]: #method.partition
1744 /// #![feature(iter_partition_in_place)]
1746 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1748 /// // Partition in-place between evens and odds
1749 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1751 /// assert_eq!(i, 3);
1752 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1753 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1755 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1756 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1758 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1759 P: FnMut(&T) -> bool,
1761 // FIXME: should we worry about the count overflowing? The only way to have more than
1762 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1764 // These closure "factory" functions exist to avoid genericity in `Self`.
1768 predicate: &'a mut impl FnMut(&T) -> bool,
1769 true_count: &'a mut usize,
1770 ) -> impl FnMut(&&mut T) -> bool + 'a {
1772 let p = predicate(&**x);
1773 *true_count += p as usize;
1779 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1780 move |x| predicate(&**x)
1783 // Repeatedly find the first `false` and swap it with the last `true`.
1784 let mut true_count = 0;
1785 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1786 if let Some(tail) = self.rfind(is_true(predicate)) {
1787 crate::mem::swap(head, tail);
1796 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1797 /// such that all those that return `true` precede all those that return `false`.
1799 /// See also [`partition()`] and [`partition_in_place()`].
1801 /// [`partition()`]: #method.partition
1802 /// [`partition_in_place()`]: #method.partition_in_place
1807 /// #![feature(iter_is_partitioned)]
1809 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1810 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1812 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1813 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1816 P: FnMut(Self::Item) -> bool,
1818 // Either all items test `true`, or the first clause stops at `false`
1819 // and we check that there are no more `true` items after that.
1820 self.all(&mut predicate) || !self.any(predicate)
1823 /// An iterator method that applies a function as long as it returns
1824 /// successfully, producing a single, final value.
1826 /// `try_fold()` takes two arguments: an initial value, and a closure with
1827 /// two arguments: an 'accumulator', and an element. The closure either
1828 /// returns successfully, with the value that the accumulator should have
1829 /// for the next iteration, or it returns failure, with an error value that
1830 /// is propagated back to the caller immediately (short-circuiting).
1832 /// The initial value is the value the accumulator will have on the first
1833 /// call. If applying the closure succeeded against every element of the
1834 /// iterator, `try_fold()` returns the final accumulator as success.
1836 /// Folding is useful whenever you have a collection of something, and want
1837 /// to produce a single value from it.
1839 /// # Note to Implementors
1841 /// Several of the other (forward) methods have default implementations in
1842 /// terms of this one, so try to implement this explicitly if it can
1843 /// do something better than the default `for` loop implementation.
1845 /// In particular, try to have this call `try_fold()` on the internal parts
1846 /// from which this iterator is composed. If multiple calls are needed,
1847 /// the `?` operator may be convenient for chaining the accumulator value
1848 /// along, but beware any invariants that need to be upheld before those
1849 /// early returns. This is a `&mut self` method, so iteration needs to be
1850 /// resumable after hitting an error here.
1857 /// let a = [1, 2, 3];
1859 /// // the checked sum of all of the elements of the array
1860 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1862 /// assert_eq!(sum, Some(6));
1865 /// Short-circuiting:
1868 /// let a = [10, 20, 30, 100, 40, 50];
1869 /// let mut it = a.iter();
1871 /// // This sum overflows when adding the 100 element
1872 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1873 /// assert_eq!(sum, None);
1875 /// // Because it short-circuited, the remaining elements are still
1876 /// // available through the iterator.
1877 /// assert_eq!(it.len(), 2);
1878 /// assert_eq!(it.next(), Some(&40));
1881 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1882 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1885 F: FnMut(B, Self::Item) -> R,
1888 let mut accum = init;
1889 while let Some(x) = self.next() {
1890 accum = f(accum, x)?;
1895 /// An iterator method that applies a fallible function to each item in the
1896 /// iterator, stopping at the first error and returning that error.
1898 /// This can also be thought of as the fallible form of [`for_each()`]
1899 /// or as the stateless version of [`try_fold()`].
1901 /// [`for_each()`]: #method.for_each
1902 /// [`try_fold()`]: #method.try_fold
1907 /// use std::fs::rename;
1908 /// use std::io::{stdout, Write};
1909 /// use std::path::Path;
1911 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1913 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1914 /// assert!(res.is_ok());
1916 /// let mut it = data.iter().cloned();
1917 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1918 /// assert!(res.is_err());
1919 /// // It short-circuited, so the remaining items are still in the iterator:
1920 /// assert_eq!(it.next(), Some("stale_bread.json"));
1923 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1924 fn try_for_each<F, R>(&mut self, f: F) -> R
1927 F: FnMut(Self::Item) -> R,
1931 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
1935 self.try_fold((), call(f))
1938 /// An iterator method that applies a function, producing a single, final value.
1940 /// `fold()` takes two arguments: an initial value, and a closure with two
1941 /// arguments: an 'accumulator', and an element. The closure returns the value that
1942 /// the accumulator should have for the next iteration.
1944 /// The initial value is the value the accumulator will have on the first
1947 /// After applying this closure to every element of the iterator, `fold()`
1948 /// returns the accumulator.
1950 /// This operation is sometimes called 'reduce' or 'inject'.
1952 /// Folding is useful whenever you have a collection of something, and want
1953 /// to produce a single value from it.
1955 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1956 /// may not terminate for infinite iterators, even on traits for which a
1957 /// result is determinable in finite time.
1959 /// # Note to Implementors
1961 /// Several of the other (forward) methods have default implementations in
1962 /// terms of this one, so try to implement this explicitly if it can
1963 /// do something better than the default `for` loop implementation.
1965 /// In particular, try to have this call `fold()` on the internal parts
1966 /// from which this iterator is composed.
1973 /// let a = [1, 2, 3];
1975 /// // the sum of all of the elements of the array
1976 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1978 /// assert_eq!(sum, 6);
1981 /// Let's walk through each step of the iteration here:
1983 /// | element | acc | x | result |
1984 /// |---------|-----|---|--------|
1986 /// | 1 | 0 | 1 | 1 |
1987 /// | 2 | 1 | 2 | 3 |
1988 /// | 3 | 3 | 3 | 6 |
1990 /// And so, our final result, `6`.
1992 /// It's common for people who haven't used iterators a lot to
1993 /// use a `for` loop with a list of things to build up a result. Those
1994 /// can be turned into `fold()`s:
1996 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1999 /// let numbers = [1, 2, 3, 4, 5];
2001 /// let mut result = 0;
2004 /// for i in &numbers {
2005 /// result = result + i;
2009 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2011 /// // they're the same
2012 /// assert_eq!(result, result2);
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2019 F: FnMut(B, Self::Item) -> B,
2021 let mut accum = init;
2022 while let Some(x) = self.next() {
2023 accum = f(accum, x);
2028 /// The same as [`fold()`](#method.fold), but uses the first element in the
2029 /// iterator as the initial value, folding every subsequent element into it.
2030 /// If the iterator is empty, return `None`; otherwise, return the result
2035 /// Find the maximum value:
2038 /// #![feature(iterator_fold_self)]
2040 /// fn find_max<I>(iter: I) -> Option<I::Item>
2041 /// where I: Iterator,
2044 /// iter.fold_first(|a, b| {
2045 /// if a >= b { a } else { b }
2048 /// let a = [10, 20, 5, -23, 0];
2049 /// let b: [u32; 0] = [];
2051 /// assert_eq!(find_max(a.iter()), Some(&20));
2052 /// assert_eq!(find_max(b.iter()), None);
2055 #[unstable(feature = "iterator_fold_self", issue = "68125")]
2056 fn fold_first<F>(mut self, f: F) -> Option<Self::Item>
2059 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2061 let first = self.next()?;
2062 Some(self.fold(first, f))
2065 /// Tests if every element of the iterator matches a predicate.
2067 /// `all()` takes a closure that returns `true` or `false`. It applies
2068 /// this closure to each element of the iterator, and if they all return
2069 /// `true`, then so does `all()`. If any of them return `false`, it
2070 /// returns `false`.
2072 /// `all()` is short-circuiting; in other words, it will stop processing
2073 /// as soon as it finds a `false`, given that no matter what else happens,
2074 /// the result will also be `false`.
2076 /// An empty iterator returns `true`.
2083 /// let a = [1, 2, 3];
2085 /// assert!(a.iter().all(|&x| x > 0));
2087 /// assert!(!a.iter().all(|&x| x > 2));
2090 /// Stopping at the first `false`:
2093 /// let a = [1, 2, 3];
2095 /// let mut iter = a.iter();
2097 /// assert!(!iter.all(|&x| x != 2));
2099 /// // we can still use `iter`, as there are more elements.
2100 /// assert_eq!(iter.next(), Some(&3));
2103 #[stable(feature = "rust1", since = "1.0.0")]
2104 fn all<F>(&mut self, f: F) -> bool
2107 F: FnMut(Self::Item) -> bool,
2110 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2112 if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) }
2115 self.try_fold((), check(f)) == LoopState::Continue(())
2118 /// Tests if any element of the iterator matches a predicate.
2120 /// `any()` takes a closure that returns `true` or `false`. It applies
2121 /// this closure to each element of the iterator, and if any of them return
2122 /// `true`, then so does `any()`. If they all return `false`, it
2123 /// returns `false`.
2125 /// `any()` is short-circuiting; in other words, it will stop processing
2126 /// as soon as it finds a `true`, given that no matter what else happens,
2127 /// the result will also be `true`.
2129 /// An empty iterator returns `false`.
2136 /// let a = [1, 2, 3];
2138 /// assert!(a.iter().any(|&x| x > 0));
2140 /// assert!(!a.iter().any(|&x| x > 5));
2143 /// Stopping at the first `true`:
2146 /// let a = [1, 2, 3];
2148 /// let mut iter = a.iter();
2150 /// assert!(iter.any(|&x| x != 2));
2152 /// // we can still use `iter`, as there are more elements.
2153 /// assert_eq!(iter.next(), Some(&2));
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 fn any<F>(&mut self, f: F) -> bool
2160 F: FnMut(Self::Item) -> bool,
2163 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2165 if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) }
2169 self.try_fold((), check(f)) == LoopState::Break(())
2172 /// Searches for an element of an iterator that satisfies a predicate.
2174 /// `find()` takes a closure that returns `true` or `false`. It applies
2175 /// this closure to each element of the iterator, and if any of them return
2176 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2177 /// `false`, it returns [`None`].
2179 /// `find()` is short-circuiting; in other words, it will stop processing
2180 /// as soon as the closure returns `true`.
2182 /// Because `find()` takes a reference, and many iterators iterate over
2183 /// references, this leads to a possibly confusing situation where the
2184 /// argument is a double reference. You can see this effect in the
2185 /// examples below, with `&&x`.
2187 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
2188 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2195 /// let a = [1, 2, 3];
2197 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2199 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2202 /// Stopping at the first `true`:
2205 /// let a = [1, 2, 3];
2207 /// let mut iter = a.iter();
2209 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2211 /// // we can still use `iter`, as there are more elements.
2212 /// assert_eq!(iter.next(), Some(&3));
2215 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2221 P: FnMut(&Self::Item) -> bool,
2225 mut predicate: impl FnMut(&T) -> bool,
2226 ) -> impl FnMut((), T) -> LoopState<(), T> {
2228 if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) }
2232 self.try_fold((), check(predicate)).break_value()
2235 /// Applies function to the elements of iterator and returns
2236 /// the first non-none result.
2238 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2244 /// let a = ["lol", "NaN", "2", "5"];
2246 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2248 /// assert_eq!(first_number, Some(2));
2251 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2252 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2255 F: FnMut(Self::Item) -> Option<B>,
2258 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> LoopState<(), B> {
2259 move |(), x| match f(x) {
2260 Some(x) => LoopState::Break(x),
2261 None => LoopState::Continue(()),
2265 self.try_fold((), check(f)).break_value()
2268 /// Applies function to the elements of iterator and returns
2269 /// the first true result or the first error.
2274 /// #![feature(try_find)]
2276 /// let a = ["1", "2", "lol", "NaN", "5"];
2278 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2279 /// Ok(s.parse::<i32>()? == search)
2282 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2283 /// assert_eq!(result, Ok(Some(&"2")));
2285 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2286 /// assert!(result.is_err());
2289 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2290 fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2293 F: FnMut(&Self::Item) -> R,
2297 fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> LoopState<(), Result<T, R::Error>>
2302 move |(), x| match f(&x).into_result() {
2303 Ok(false) => LoopState::Continue(()),
2304 Ok(true) => LoopState::Break(Ok(x)),
2305 Err(x) => LoopState::Break(Err(x)),
2309 self.try_fold((), check(f)).break_value().transpose()
2312 /// Searches for an element in an iterator, returning its index.
2314 /// `position()` takes a closure that returns `true` or `false`. It applies
2315 /// this closure to each element of the iterator, and if one of them
2316 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2317 /// them return `false`, it returns [`None`].
2319 /// `position()` is short-circuiting; in other words, it will stop
2320 /// processing as soon as it finds a `true`.
2322 /// # Overflow Behavior
2324 /// The method does no guarding against overflows, so if there are more
2325 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2326 /// result or panics. If debug assertions are enabled, a panic is
2331 /// This function might panic if the iterator has more than `usize::MAX`
2332 /// non-matching elements.
2334 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2335 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2336 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
2343 /// let a = [1, 2, 3];
2345 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2347 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2350 /// Stopping at the first `true`:
2353 /// let a = [1, 2, 3, 4];
2355 /// let mut iter = a.iter();
2357 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2359 /// // we can still use `iter`, as there are more elements.
2360 /// assert_eq!(iter.next(), Some(&3));
2362 /// // The returned index depends on iterator state
2363 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2367 #[stable(feature = "rust1", since = "1.0.0")]
2368 fn position<P>(&mut self, predicate: P) -> Option<usize>
2371 P: FnMut(Self::Item) -> bool,
2375 mut predicate: impl FnMut(T) -> bool,
2376 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2377 // The addition might panic on overflow
2379 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) }
2383 self.try_fold(0, check(predicate)).break_value()
2386 /// Searches for an element in an iterator from the right, returning its
2389 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2390 /// this closure to each element of the iterator, starting from the end,
2391 /// and if one of them returns `true`, then `rposition()` returns
2392 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2394 /// `rposition()` is short-circuiting; in other words, it will stop
2395 /// processing as soon as it finds a `true`.
2397 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2398 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2405 /// let a = [1, 2, 3];
2407 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2409 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2412 /// Stopping at the first `true`:
2415 /// let a = [1, 2, 3];
2417 /// let mut iter = a.iter();
2419 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2421 /// // we can still use `iter`, as there are more elements.
2422 /// assert_eq!(iter.next(), Some(&1));
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2428 P: FnMut(Self::Item) -> bool,
2429 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2431 // No need for an overflow check here, because `ExactSizeIterator`
2432 // implies that the number of elements fits into a `usize`.
2435 mut predicate: impl FnMut(T) -> bool,
2436 ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2439 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) }
2444 self.try_rfold(n, check(predicate)).break_value()
2447 /// Returns the maximum element of an iterator.
2449 /// If several elements are equally maximum, the last element is
2450 /// returned. If the iterator is empty, [`None`] is returned.
2452 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2459 /// let a = [1, 2, 3];
2460 /// let b: Vec<u32> = Vec::new();
2462 /// assert_eq!(a.iter().max(), Some(&3));
2463 /// assert_eq!(b.iter().max(), None);
2466 #[stable(feature = "rust1", since = "1.0.0")]
2467 fn max(self) -> Option<Self::Item>
2472 self.max_by(Ord::cmp)
2475 /// Returns the minimum element of an iterator.
2477 /// If several elements are equally minimum, the first element is
2478 /// returned. If the iterator is empty, [`None`] is returned.
2480 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2487 /// let a = [1, 2, 3];
2488 /// let b: Vec<u32> = Vec::new();
2490 /// assert_eq!(a.iter().min(), Some(&1));
2491 /// assert_eq!(b.iter().min(), None);
2494 #[stable(feature = "rust1", since = "1.0.0")]
2495 fn min(self) -> Option<Self::Item>
2500 self.min_by(Ord::cmp)
2503 /// Returns the element that gives the maximum value from the
2504 /// specified function.
2506 /// If several elements are equally maximum, the last element is
2507 /// returned. If the iterator is empty, [`None`] is returned.
2509 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2514 /// let a = [-3_i32, 0, 1, 5, -10];
2515 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2518 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2519 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2522 F: FnMut(&Self::Item) -> B,
2525 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2530 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2534 let (_, x) = self.map(key(f)).max_by(compare)?;
2538 /// Returns the element that gives the maximum value with respect to the
2539 /// specified comparison function.
2541 /// If several elements are equally maximum, the last element is
2542 /// returned. If the iterator is empty, [`None`] is returned.
2544 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2549 /// let a = [-3_i32, 0, 1, 5, -10];
2550 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2553 #[stable(feature = "iter_max_by", since = "1.15.0")]
2554 fn max_by<F>(self, compare: F) -> Option<Self::Item>
2557 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2560 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2561 move |x, y| cmp::max_by(x, y, &mut compare)
2564 self.fold_first(fold(compare))
2567 /// Returns the element that gives the minimum value from the
2568 /// specified function.
2570 /// If several elements are equally minimum, the first element is
2571 /// returned. If the iterator is empty, [`None`] is returned.
2573 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2578 /// let a = [-3_i32, 0, 1, 5, -10];
2579 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2582 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2583 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2586 F: FnMut(&Self::Item) -> B,
2589 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2594 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2598 let (_, x) = self.map(key(f)).min_by(compare)?;
2602 /// Returns the element that gives the minimum value with respect to the
2603 /// specified comparison function.
2605 /// If several elements are equally minimum, the first element is
2606 /// returned. If the iterator is empty, [`None`] is returned.
2608 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2613 /// let a = [-3_i32, 0, 1, 5, -10];
2614 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2617 #[stable(feature = "iter_min_by", since = "1.15.0")]
2618 fn min_by<F>(self, compare: F) -> Option<Self::Item>
2621 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2624 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2625 move |x, y| cmp::min_by(x, y, &mut compare)
2628 self.fold_first(fold(compare))
2631 /// Reverses an iterator's direction.
2633 /// Usually, iterators iterate from left to right. After using `rev()`,
2634 /// an iterator will instead iterate from right to left.
2636 /// This is only possible if the iterator has an end, so `rev()` only
2637 /// works on [`DoubleEndedIterator`]s.
2639 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2644 /// let a = [1, 2, 3];
2646 /// let mut iter = a.iter().rev();
2648 /// assert_eq!(iter.next(), Some(&3));
2649 /// assert_eq!(iter.next(), Some(&2));
2650 /// assert_eq!(iter.next(), Some(&1));
2652 /// assert_eq!(iter.next(), None);
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 fn rev(self) -> Rev<Self>
2658 Self: Sized + DoubleEndedIterator,
2663 /// Converts an iterator of pairs into a pair of containers.
2665 /// `unzip()` consumes an entire iterator of pairs, producing two
2666 /// collections: one from the left elements of the pairs, and one
2667 /// from the right elements.
2669 /// This function is, in some sense, the opposite of [`zip`].
2671 /// [`zip`]: #method.zip
2678 /// let a = [(1, 2), (3, 4)];
2680 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2682 /// assert_eq!(left, [1, 3]);
2683 /// assert_eq!(right, [2, 4]);
2685 #[stable(feature = "rust1", since = "1.0.0")]
2686 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2688 FromA: Default + Extend<A>,
2689 FromB: Default + Extend<B>,
2690 Self: Sized + Iterator<Item = (A, B)>,
2692 fn extend<'a, A, B>(
2693 ts: &'a mut impl Extend<A>,
2694 us: &'a mut impl Extend<B>,
2695 ) -> impl FnMut((), (A, B)) + 'a {
2702 let mut ts: FromA = Default::default();
2703 let mut us: FromB = Default::default();
2705 let (lower_bound, _) = self.size_hint();
2706 if lower_bound > 0 {
2707 ts.extend_reserve(lower_bound);
2708 us.extend_reserve(lower_bound);
2711 self.fold((), extend(&mut ts, &mut us));
2716 /// Creates an iterator which copies all of its elements.
2718 /// This is useful when you have an iterator over `&T`, but you need an
2719 /// iterator over `T`.
2726 /// let a = [1, 2, 3];
2728 /// let v_copied: Vec<_> = a.iter().copied().collect();
2730 /// // copied is the same as .map(|&x| x)
2731 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2733 /// assert_eq!(v_copied, vec![1, 2, 3]);
2734 /// assert_eq!(v_map, vec![1, 2, 3]);
2736 #[stable(feature = "iter_copied", since = "1.36.0")]
2737 fn copied<'a, T: 'a>(self) -> Copied<Self>
2739 Self: Sized + Iterator<Item = &'a T>,
2745 /// Creates an iterator which [`clone`]s all of its elements.
2747 /// This is useful when you have an iterator over `&T`, but you need an
2748 /// iterator over `T`.
2750 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2757 /// let a = [1, 2, 3];
2759 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2761 /// // cloned is the same as .map(|&x| x), for integers
2762 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2764 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2765 /// assert_eq!(v_map, vec![1, 2, 3]);
2767 #[stable(feature = "rust1", since = "1.0.0")]
2768 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2770 Self: Sized + Iterator<Item = &'a T>,
2776 /// Repeats an iterator endlessly.
2778 /// Instead of stopping at [`None`], the iterator will instead start again,
2779 /// from the beginning. After iterating again, it will start at the
2780 /// beginning again. And again. And again. Forever.
2782 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2789 /// let a = [1, 2, 3];
2791 /// let mut it = a.iter().cycle();
2793 /// assert_eq!(it.next(), Some(&1));
2794 /// assert_eq!(it.next(), Some(&2));
2795 /// assert_eq!(it.next(), Some(&3));
2796 /// assert_eq!(it.next(), Some(&1));
2797 /// assert_eq!(it.next(), Some(&2));
2798 /// assert_eq!(it.next(), Some(&3));
2799 /// assert_eq!(it.next(), Some(&1));
2801 #[stable(feature = "rust1", since = "1.0.0")]
2803 fn cycle(self) -> Cycle<Self>
2805 Self: Sized + Clone,
2810 /// Sums the elements of an iterator.
2812 /// Takes each element, adds them together, and returns the result.
2814 /// An empty iterator returns the zero value of the type.
2818 /// When calling `sum()` and a primitive integer type is being returned, this
2819 /// method will panic if the computation overflows and debug assertions are
2827 /// let a = [1, 2, 3];
2828 /// let sum: i32 = a.iter().sum();
2830 /// assert_eq!(sum, 6);
2832 #[stable(feature = "iter_arith", since = "1.11.0")]
2833 fn sum<S>(self) -> S
2841 /// Iterates over the entire iterator, multiplying all the elements
2843 /// An empty iterator returns the one value of the type.
2847 /// When calling `product()` and a primitive integer type is being returned,
2848 /// method will panic if the computation overflows and debug assertions are
2854 /// fn factorial(n: u32) -> u32 {
2855 /// (1..=n).product()
2857 /// assert_eq!(factorial(0), 1);
2858 /// assert_eq!(factorial(1), 1);
2859 /// assert_eq!(factorial(5), 120);
2861 #[stable(feature = "iter_arith", since = "1.11.0")]
2862 fn product<P>(self) -> P
2865 P: Product<Self::Item>,
2867 Product::product(self)
2870 /// Lexicographically compares the elements of this `Iterator` with those
2876 /// use std::cmp::Ordering;
2878 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2879 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2880 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2882 #[stable(feature = "iter_order", since = "1.5.0")]
2883 fn cmp<I>(self, other: I) -> Ordering
2885 I: IntoIterator<Item = Self::Item>,
2889 self.cmp_by(other, |x, y| x.cmp(&y))
2892 /// Lexicographically compares the elements of this `Iterator` with those
2893 /// of another with respect to the specified comparison function.
2900 /// #![feature(iter_order_by)]
2902 /// use std::cmp::Ordering;
2904 /// let xs = [1, 2, 3, 4];
2905 /// let ys = [1, 4, 9, 16];
2907 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2908 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2909 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2911 #[unstable(feature = "iter_order_by", issue = "64295")]
2912 fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
2916 F: FnMut(Self::Item, I::Item) -> Ordering,
2918 let mut other = other.into_iter();
2921 let x = match self.next() {
2923 if other.next().is_none() {
2924 return Ordering::Equal;
2926 return Ordering::Less;
2932 let y = match other.next() {
2933 None => return Ordering::Greater,
2938 Ordering::Equal => (),
2939 non_eq => return non_eq,
2944 /// Lexicographically compares the elements of this `Iterator` with those
2950 /// use std::cmp::Ordering;
2952 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2953 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2954 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2956 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2958 #[stable(feature = "iter_order", since = "1.5.0")]
2959 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
2962 Self::Item: PartialOrd<I::Item>,
2965 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
2968 /// Lexicographically compares the elements of this `Iterator` with those
2969 /// of another with respect to the specified comparison function.
2976 /// #![feature(iter_order_by)]
2978 /// use std::cmp::Ordering;
2980 /// let xs = [1.0, 2.0, 3.0, 4.0];
2981 /// let ys = [1.0, 4.0, 9.0, 16.0];
2984 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2985 /// Some(Ordering::Less)
2988 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2989 /// Some(Ordering::Equal)
2992 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2993 /// Some(Ordering::Greater)
2996 #[unstable(feature = "iter_order_by", issue = "64295")]
2997 fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
3001 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3003 let mut other = other.into_iter();
3006 let x = match self.next() {
3008 if other.next().is_none() {
3009 return Some(Ordering::Equal);
3011 return Some(Ordering::Less);
3017 let y = match other.next() {
3018 None => return Some(Ordering::Greater),
3022 match partial_cmp(x, y) {
3023 Some(Ordering::Equal) => (),
3024 non_eq => return non_eq,
3029 /// Determines if the elements of this `Iterator` are equal to those of
3035 /// assert_eq!([1].iter().eq([1].iter()), true);
3036 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3038 #[stable(feature = "iter_order", since = "1.5.0")]
3039 fn eq<I>(self, other: I) -> bool
3042 Self::Item: PartialEq<I::Item>,
3045 self.eq_by(other, |x, y| x == y)
3048 /// Determines if the elements of this `Iterator` are equal to those of
3049 /// another with respect to the specified equality function.
3056 /// #![feature(iter_order_by)]
3058 /// let xs = [1, 2, 3, 4];
3059 /// let ys = [1, 4, 9, 16];
3061 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3063 #[unstable(feature = "iter_order_by", issue = "64295")]
3064 fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3068 F: FnMut(Self::Item, I::Item) -> bool,
3070 let mut other = other.into_iter();
3073 let x = match self.next() {
3074 None => return other.next().is_none(),
3078 let y = match other.next() {
3079 None => return false,
3089 /// Determines if the elements of this `Iterator` are unequal to those of
3095 /// assert_eq!([1].iter().ne([1].iter()), false);
3096 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3098 #[stable(feature = "iter_order", since = "1.5.0")]
3099 fn ne<I>(self, other: I) -> bool
3102 Self::Item: PartialEq<I::Item>,
3108 /// Determines if the elements of this `Iterator` are lexicographically
3109 /// less than those of another.
3114 /// assert_eq!([1].iter().lt([1].iter()), false);
3115 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3116 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3118 #[stable(feature = "iter_order", since = "1.5.0")]
3119 fn lt<I>(self, other: I) -> bool
3122 Self::Item: PartialOrd<I::Item>,
3125 self.partial_cmp(other) == Some(Ordering::Less)
3128 /// Determines if the elements of this `Iterator` are lexicographically
3129 /// less or equal to those of another.
3134 /// assert_eq!([1].iter().le([1].iter()), true);
3135 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3136 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3138 #[stable(feature = "iter_order", since = "1.5.0")]
3139 fn le<I>(self, other: I) -> bool
3142 Self::Item: PartialOrd<I::Item>,
3145 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3148 /// Determines if the elements of this `Iterator` are lexicographically
3149 /// greater than those of another.
3154 /// assert_eq!([1].iter().gt([1].iter()), false);
3155 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3156 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3158 #[stable(feature = "iter_order", since = "1.5.0")]
3159 fn gt<I>(self, other: I) -> bool
3162 Self::Item: PartialOrd<I::Item>,
3165 self.partial_cmp(other) == Some(Ordering::Greater)
3168 /// Determines if the elements of this `Iterator` are lexicographically
3169 /// greater than or equal to those of another.
3174 /// assert_eq!([1].iter().ge([1].iter()), true);
3175 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3176 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3178 #[stable(feature = "iter_order", since = "1.5.0")]
3179 fn ge<I>(self, other: I) -> bool
3182 Self::Item: PartialOrd<I::Item>,
3185 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3188 /// Checks if the elements of this iterator are sorted.
3190 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3191 /// iterator yields exactly zero or one element, `true` is returned.
3193 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3194 /// implies that this function returns `false` if any two consecutive items are not
3200 /// #![feature(is_sorted)]
3202 /// assert!([1, 2, 2, 9].iter().is_sorted());
3203 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3204 /// assert!([0].iter().is_sorted());
3205 /// assert!(std::iter::empty::<i32>().is_sorted());
3206 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3209 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3210 fn is_sorted(self) -> bool
3213 Self::Item: PartialOrd,
3215 self.is_sorted_by(PartialOrd::partial_cmp)
3218 /// Checks if the elements of this iterator are sorted using the given comparator function.
3220 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3221 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3222 /// [`is_sorted`]; see its documentation for more information.
3227 /// #![feature(is_sorted)]
3229 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3230 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3231 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3232 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3233 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3236 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3237 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3238 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3241 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3243 let mut last = match self.next() {
3245 None => return true,
3248 while let Some(curr) = self.next() {
3249 if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3258 /// Checks if the elements of this iterator are sorted using the given key extraction
3261 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3262 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3263 /// its documentation for more information.
3265 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3270 /// #![feature(is_sorted)]
3272 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3273 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3276 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3277 fn is_sorted_by_key<F, K>(self, f: F) -> bool
3280 F: FnMut(Self::Item) -> K,
3283 self.map(f).is_sorted()
3287 #[stable(feature = "rust1", since = "1.0.0")]
3288 impl<I: Iterator + ?Sized> Iterator for &mut I {
3289 type Item = I::Item;
3290 fn next(&mut self) -> Option<I::Item> {
3293 fn size_hint(&self) -> (usize, Option<usize>) {
3294 (**self).size_hint()
3296 fn nth(&mut self, n: usize) -> Option<Self::Item> {