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"
95 #[must_use = "iterators are lazy and do nothing unless consumed"]
97 /// The type of the elements being iterated over.
98 #[stable(feature = "rust1", since = "1.0.0")]
101 /// Advances the iterator and returns the next value.
103 /// Returns [`None`] when iteration is finished. Individual iterator
104 /// implementations may choose to resume iteration, and so calling `next()`
105 /// again may or may not eventually start returning [`Some(Item)`] again at some
108 /// [`None`]: ../../std/option/enum.Option.html#variant.None
109 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
116 /// let a = [1, 2, 3];
118 /// let mut iter = a.iter();
120 /// // A call to next() returns the next value...
121 /// assert_eq!(Some(&1), iter.next());
122 /// assert_eq!(Some(&2), iter.next());
123 /// assert_eq!(Some(&3), iter.next());
125 /// // ... and then None once it's over.
126 /// assert_eq!(None, iter.next());
128 /// // More calls may or may not return `None`. Here, they always will.
129 /// assert_eq!(None, iter.next());
130 /// assert_eq!(None, iter.next());
132 #[stable(feature = "rust1", since = "1.0.0")]
133 fn next(&mut self) -> Option
<Self::Item
>;
135 /// Returns the bounds on the remaining length of the iterator.
137 /// Specifically, `size_hint()` returns a tuple where the first element
138 /// is the lower bound, and the second element is the upper bound.
140 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
141 /// A [`None`] here means that either there is no known upper bound, or the
142 /// upper bound is larger than [`usize`].
144 /// # Implementation notes
146 /// It is not enforced that an iterator implementation yields the declared
147 /// number of elements. A buggy iterator may yield less than the lower bound
148 /// or more than the upper bound of elements.
150 /// `size_hint()` is primarily intended to be used for optimizations such as
151 /// reserving space for the elements of the iterator, but must not be
152 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
153 /// implementation of `size_hint()` should not lead to memory safety
156 /// That said, the implementation should provide a correct estimation,
157 /// because otherwise it would be a violation of the trait's protocol.
159 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
162 /// [`usize`]: ../../std/primitive.usize.html
163 /// [`Option`]: ../../std/option/enum.Option.html
164 /// [`None`]: ../../std/option/enum.Option.html#variant.None
171 /// let a = [1, 2, 3];
172 /// let iter = a.iter();
174 /// assert_eq!((3, Some(3)), iter.size_hint());
177 /// A more complex example:
180 /// // The even numbers from zero to ten.
181 /// let iter = (0..10).filter(|x| x % 2 == 0);
183 /// // We might iterate from zero to ten times. Knowing that it's five
184 /// // exactly wouldn't be possible without executing filter().
185 /// assert_eq!((0, Some(10)), iter.size_hint());
187 /// // Let's add five more numbers with chain()
188 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
190 /// // now both bounds are increased by five
191 /// assert_eq!((5, Some(15)), iter.size_hint());
194 /// Returning `None` for an upper bound:
197 /// // an infinite iterator has no upper bound
198 /// // and the maximum possible lower bound
201 /// assert_eq!((usize::MAX, None), iter.size_hint());
204 #[stable(feature = "rust1", since = "1.0.0")]
205 fn size_hint(&self) -> (usize, Option
<usize>) {
209 /// Consumes the iterator, counting the number of iterations and returning it.
211 /// This method will call [`next`] repeatedly until [`None`] is encountered,
212 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213 /// called at least once even if the iterator does not have any elements.
215 /// [`next`]: #tymethod.next
216 /// [`None`]: ../../std/option/enum.Option.html#variant.None
217 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
219 /// # Overflow Behavior
221 /// The method does no guarding against overflows, so counting elements of
222 /// an iterator with more than [`usize::MAX`] elements either produces the
223 /// wrong result or panics. If debug assertions are enabled, a panic is
228 /// This function might panic if the iterator has more than [`usize::MAX`]
231 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
238 /// let a = [1, 2, 3];
239 /// assert_eq!(a.iter().count(), 3);
241 /// let a = [1, 2, 3, 4, 5];
242 /// assert_eq!(a.iter().count(), 5);
245 #[stable(feature = "rust1", since = "1.0.0")]
246 fn count(self) -> usize
251 fn add1
<T
>(count
: usize, _
: T
) -> usize {
259 /// Consumes the iterator, returning the last element.
261 /// This method will evaluate the iterator until it returns [`None`]. While
262 /// doing so, it keeps track of the current element. After [`None`] is
263 /// returned, `last()` will then return the last element it saw.
265 /// [`None`]: ../../std/option/enum.Option.html#variant.None
272 /// let a = [1, 2, 3];
273 /// assert_eq!(a.iter().last(), Some(&3));
275 /// let a = [1, 2, 3, 4, 5];
276 /// assert_eq!(a.iter().last(), Some(&5));
279 #[stable(feature = "rust1", since = "1.0.0")]
280 fn last(self) -> Option
<Self::Item
>
285 fn some
<T
>(_
: Option
<T
>, x
: T
) -> Option
<T
> {
289 self.fold(None
, some
)
292 /// Returns the `n`th element of the iterator.
294 /// Like most indexing operations, the count starts from zero, so `nth(0)`
295 /// returns the first value, `nth(1)` the second, and so on.
297 /// Note that all preceding elements, as well as the returned element, will be
298 /// consumed from the iterator. That means that the preceding elements will be
299 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
300 /// will return different elements.
302 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
305 /// [`None`]: ../../std/option/enum.Option.html#variant.None
312 /// let a = [1, 2, 3];
313 /// assert_eq!(a.iter().nth(1), Some(&2));
316 /// Calling `nth()` multiple times doesn't rewind the iterator:
319 /// let a = [1, 2, 3];
321 /// let mut iter = a.iter();
323 /// assert_eq!(iter.nth(1), Some(&2));
324 /// assert_eq!(iter.nth(1), None);
327 /// Returning `None` if there are less than `n + 1` elements:
330 /// let a = [1, 2, 3];
331 /// assert_eq!(a.iter().nth(10), None);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 fn nth(&mut self, mut n
: usize) -> Option
<Self::Item
> {
345 /// Creates an iterator starting at the same point, but stepping by
346 /// the given amount at each iteration.
348 /// Note 1: The first element of the iterator will always be returned,
349 /// regardless of the step given.
351 /// Note 2: The time at which ignored elements are pulled is not fixed.
352 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
353 /// but is also free to behave like the sequence
354 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
355 /// Which way is used may change for some iterators for performance reasons.
356 /// The second way will advance the iterator earlier and may consume more items.
358 /// `advance_n_and_return_first` is the equivalent of:
360 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
364 /// let next = iter.next();
365 /// if total_step > 1 {
366 /// iter.nth(total_step-2);
374 /// The method will panic if the given step is `0`.
381 /// let a = [0, 1, 2, 3, 4, 5];
382 /// let mut iter = a.iter().step_by(2);
384 /// assert_eq!(iter.next(), Some(&0));
385 /// assert_eq!(iter.next(), Some(&2));
386 /// assert_eq!(iter.next(), Some(&4));
387 /// assert_eq!(iter.next(), None);
390 #[stable(feature = "iterator_step_by", since = "1.28.0")]
391 fn step_by(self, step
: usize) -> StepBy
<Self>
395 StepBy
::new(self, step
)
398 /// Takes two iterators and creates a new iterator over both in sequence.
400 /// `chain()` will return a new iterator which will first iterate over
401 /// values from the first iterator and then over values from the second
404 /// In other words, it links two iterators together, in a chain. 🔗
406 /// [`once`] is commonly used to adapt a single value into a chain of
407 /// other kinds of iteration.
414 /// let a1 = [1, 2, 3];
415 /// let a2 = [4, 5, 6];
417 /// let mut iter = a1.iter().chain(a2.iter());
419 /// assert_eq!(iter.next(), Some(&1));
420 /// assert_eq!(iter.next(), Some(&2));
421 /// assert_eq!(iter.next(), Some(&3));
422 /// assert_eq!(iter.next(), Some(&4));
423 /// assert_eq!(iter.next(), Some(&5));
424 /// assert_eq!(iter.next(), Some(&6));
425 /// assert_eq!(iter.next(), None);
428 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
429 /// anything that can be converted into an [`Iterator`], not just an
430 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
431 /// [`IntoIterator`], and so can be passed to `chain()` directly:
434 /// let s1 = &[1, 2, 3];
435 /// let s2 = &[4, 5, 6];
437 /// let mut iter = s1.iter().chain(s2);
439 /// assert_eq!(iter.next(), Some(&1));
440 /// assert_eq!(iter.next(), Some(&2));
441 /// assert_eq!(iter.next(), Some(&3));
442 /// assert_eq!(iter.next(), Some(&4));
443 /// assert_eq!(iter.next(), Some(&5));
444 /// assert_eq!(iter.next(), Some(&6));
445 /// assert_eq!(iter.next(), None);
448 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
452 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
453 /// use std::os::windows::ffi::OsStrExt;
454 /// s.encode_wide().chain(std::iter::once(0)).collect()
458 /// [`once`]: fn.once.html
459 /// [`Iterator`]: trait.Iterator.html
460 /// [`IntoIterator`]: trait.IntoIterator.html
461 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
463 #[stable(feature = "rust1", since = "1.0.0")]
464 fn chain
<U
>(self, other
: U
) -> Chain
<Self, U
::IntoIter
>
467 U
: IntoIterator
<Item
= Self::Item
>,
469 Chain
::new(self, other
.into_iter())
472 /// 'Zips up' two iterators into a single iterator of pairs.
474 /// `zip()` returns a new iterator that will iterate over two other
475 /// iterators, returning a tuple where the first element comes from the
476 /// first iterator, and the second element comes from the second iterator.
478 /// In other words, it zips two iterators together, into a single one.
480 /// If either iterator returns [`None`], [`next`] from the zipped iterator
481 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
482 /// short-circuit and `next` will not be called on the second iterator.
489 /// let a1 = [1, 2, 3];
490 /// let a2 = [4, 5, 6];
492 /// let mut iter = a1.iter().zip(a2.iter());
494 /// assert_eq!(iter.next(), Some((&1, &4)));
495 /// assert_eq!(iter.next(), Some((&2, &5)));
496 /// assert_eq!(iter.next(), Some((&3, &6)));
497 /// assert_eq!(iter.next(), None);
500 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
501 /// anything that can be converted into an [`Iterator`], not just an
502 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
503 /// [`IntoIterator`], and so can be passed to `zip()` directly:
505 /// [`IntoIterator`]: trait.IntoIterator.html
506 /// [`Iterator`]: trait.Iterator.html
509 /// let s1 = &[1, 2, 3];
510 /// let s2 = &[4, 5, 6];
512 /// let mut iter = s1.iter().zip(s2);
514 /// assert_eq!(iter.next(), Some((&1, &4)));
515 /// assert_eq!(iter.next(), Some((&2, &5)));
516 /// assert_eq!(iter.next(), Some((&3, &6)));
517 /// assert_eq!(iter.next(), None);
520 /// `zip()` is often used to zip an infinite iterator to a finite one.
521 /// This works because the finite iterator will eventually return [`None`],
522 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
525 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
527 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
529 /// assert_eq!((0, 'f'), enumerate[0]);
530 /// assert_eq!((0, 'f'), zipper[0]);
532 /// assert_eq!((1, 'o'), enumerate[1]);
533 /// assert_eq!((1, 'o'), zipper[1]);
535 /// assert_eq!((2, 'o'), enumerate[2]);
536 /// assert_eq!((2, 'o'), zipper[2]);
539 /// [`enumerate`]: trait.Iterator.html#method.enumerate
540 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
541 /// [`None`]: ../../std/option/enum.Option.html#variant.None
543 #[stable(feature = "rust1", since = "1.0.0")]
544 fn zip
<U
>(self, other
: U
) -> Zip
<Self, U
::IntoIter
>
549 Zip
::new(self, other
.into_iter())
552 /// Takes a closure and creates an iterator which calls that closure on each
555 /// `map()` transforms one iterator into another, by means of its argument:
556 /// something that implements [`FnMut`]. It produces a new iterator which
557 /// calls this closure on each element of the original iterator.
559 /// If you are good at thinking in types, you can think of `map()` like this:
560 /// If you have an iterator that gives you elements of some type `A`, and
561 /// you want an iterator of some other type `B`, you can use `map()`,
562 /// passing a closure that takes an `A` and returns a `B`.
564 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
565 /// lazy, it is best used when you're already working with other iterators.
566 /// If you're doing some sort of looping for a side effect, it's considered
567 /// more idiomatic to use [`for`] than `map()`.
569 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
570 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
577 /// let a = [1, 2, 3];
579 /// let mut iter = a.iter().map(|x| 2 * x);
581 /// assert_eq!(iter.next(), Some(2));
582 /// assert_eq!(iter.next(), Some(4));
583 /// assert_eq!(iter.next(), Some(6));
584 /// assert_eq!(iter.next(), None);
587 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
590 /// # #![allow(unused_must_use)]
591 /// // don't do this:
592 /// (0..5).map(|x| println!("{}", x));
594 /// // it won't even execute, as it is lazy. Rust will warn you about this.
596 /// // Instead, use for:
598 /// println!("{}", x);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 fn map
<B
, F
>(self, f
: F
) -> Map
<Self, F
>
606 F
: FnMut(Self::Item
) -> B
,
611 /// Calls a closure on each element of an iterator.
613 /// This is equivalent to using a [`for`] loop on the iterator, although
614 /// `break` and `continue` are not possible from a closure. It's generally
615 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
616 /// when processing items at the end of longer iterator chains. In some
617 /// cases `for_each` may also be faster than a loop, because it will use
618 /// internal iteration on adaptors like `Chain`.
620 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
627 /// use std::sync::mpsc::channel;
629 /// let (tx, rx) = channel();
630 /// (0..5).map(|x| x * 2 + 1)
631 /// .for_each(move |x| tx.send(x).unwrap());
633 /// let v: Vec<_> = rx.iter().collect();
634 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
637 /// For such a small example, a `for` loop may be cleaner, but `for_each`
638 /// might be preferable to keep a functional style with longer iterators:
641 /// (0..5).flat_map(|x| x * 100 .. x * 110)
643 /// .filter(|&(i, x)| (i + x) % 3 == 0)
644 /// .for_each(|(i, x)| println!("{}:{}", i, x));
647 #[stable(feature = "iterator_for_each", since = "1.21.0")]
648 fn for_each
<F
>(self, f
: F
)
651 F
: FnMut(Self::Item
),
654 fn call
<T
>(mut f
: impl FnMut(T
)) -> impl FnMut((), T
) {
655 move |(), item
| f(item
)
658 self.fold((), call(f
));
661 /// Creates an iterator which uses a closure to determine if an element
662 /// should be yielded.
664 /// The closure must return `true` or `false`. `filter()` creates an
665 /// iterator which calls this closure on each element. If the closure
666 /// returns `true`, then the element is returned. If the closure returns
667 /// `false`, it will try again, and call the closure on the next element,
668 /// seeing if it passes the test.
675 /// let a = [0i32, 1, 2];
677 /// let mut iter = a.iter().filter(|x| x.is_positive());
679 /// assert_eq!(iter.next(), Some(&1));
680 /// assert_eq!(iter.next(), Some(&2));
681 /// assert_eq!(iter.next(), None);
684 /// Because the closure passed to `filter()` takes a reference, and many
685 /// iterators iterate over references, this leads to a possibly confusing
686 /// situation, where the type of the closure is a double reference:
689 /// let a = [0, 1, 2];
691 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
693 /// assert_eq!(iter.next(), Some(&2));
694 /// assert_eq!(iter.next(), None);
697 /// It's common to instead use destructuring on the argument to strip away
701 /// let a = [0, 1, 2];
703 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
705 /// assert_eq!(iter.next(), Some(&2));
706 /// assert_eq!(iter.next(), None);
712 /// let a = [0, 1, 2];
714 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
716 /// assert_eq!(iter.next(), Some(&2));
717 /// assert_eq!(iter.next(), None);
722 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn filter
<P
>(self, predicate
: P
) -> Filter
<Self, P
>
728 P
: FnMut(&Self::Item
) -> bool
,
730 Filter
::new(self, predicate
)
733 /// Creates an iterator that both filters and maps.
735 /// The closure must return an [`Option<T>`]. `filter_map` creates an
736 /// iterator which calls this closure on each element. If the closure
737 /// returns [`Some(element)`][`Some`], then that element is returned. If the
738 /// closure returns [`None`], it will try again, and call the closure on the
739 /// next element, seeing if it will return [`Some`].
741 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
744 /// [`filter`]: #method.filter
745 /// [`map`]: #method.map
747 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
749 /// In other words, it removes the [`Option<T>`] layer automatically. If your
750 /// mapping is already returning an [`Option<T>`] and you want to skip over
751 /// [`None`]s, then `filter_map` is much, much nicer to use.
758 /// let a = ["1", "lol", "3", "NaN", "5"];
760 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
762 /// assert_eq!(iter.next(), Some(1));
763 /// assert_eq!(iter.next(), Some(3));
764 /// assert_eq!(iter.next(), Some(5));
765 /// assert_eq!(iter.next(), None);
768 /// Here's the same example, but with [`filter`] and [`map`]:
771 /// let a = ["1", "lol", "3", "NaN", "5"];
772 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
773 /// assert_eq!(iter.next(), Some(1));
774 /// assert_eq!(iter.next(), Some(3));
775 /// assert_eq!(iter.next(), Some(5));
776 /// assert_eq!(iter.next(), None);
779 /// [`Option<T>`]: ../../std/option/enum.Option.html
780 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
781 /// [`None`]: ../../std/option/enum.Option.html#variant.None
783 #[stable(feature = "rust1", since = "1.0.0")]
784 fn filter_map
<B
, F
>(self, f
: F
) -> FilterMap
<Self, F
>
787 F
: FnMut(Self::Item
) -> Option
<B
>,
789 FilterMap
::new(self, f
)
792 /// Creates an iterator which gives the current iteration count as well as
795 /// The iterator returned yields pairs `(i, val)`, where `i` is the
796 /// current index of iteration and `val` is the value returned by the
799 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
800 /// different sized integer, the [`zip`] function provides similar
803 /// # Overflow Behavior
805 /// The method does no guarding against overflows, so enumerating more than
806 /// [`usize::MAX`] elements either produces the wrong result or panics. If
807 /// debug assertions are enabled, a panic is guaranteed.
811 /// The returned iterator might panic if the to-be-returned index would
812 /// overflow a [`usize`].
814 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
815 /// [`usize`]: ../../std/primitive.usize.html
816 /// [`zip`]: #method.zip
821 /// let a = ['a', 'b', 'c'];
823 /// let mut iter = a.iter().enumerate();
825 /// assert_eq!(iter.next(), Some((0, &'a')));
826 /// assert_eq!(iter.next(), Some((1, &'b')));
827 /// assert_eq!(iter.next(), Some((2, &'c')));
828 /// assert_eq!(iter.next(), None);
831 #[stable(feature = "rust1", since = "1.0.0")]
832 fn enumerate(self) -> Enumerate
<Self>
839 /// Creates an iterator which can use `peek` to look at the next element of
840 /// the iterator without consuming it.
842 /// Adds a [`peek`] method to an iterator. See its documentation for
843 /// more information.
845 /// Note that the underlying iterator is still advanced when [`peek`] is
846 /// called for the first time: In order to retrieve the next element,
847 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
848 /// anything other than fetching the next value) of the [`next`] method
851 /// [`peek`]: struct.Peekable.html#method.peek
852 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
859 /// let xs = [1, 2, 3];
861 /// let mut iter = xs.iter().peekable();
863 /// // peek() lets us see into the future
864 /// assert_eq!(iter.peek(), Some(&&1));
865 /// assert_eq!(iter.next(), Some(&1));
867 /// assert_eq!(iter.next(), Some(&2));
869 /// // we can peek() multiple times, the iterator won't advance
870 /// assert_eq!(iter.peek(), Some(&&3));
871 /// assert_eq!(iter.peek(), Some(&&3));
873 /// assert_eq!(iter.next(), Some(&3));
875 /// // after the iterator is finished, so is peek()
876 /// assert_eq!(iter.peek(), None);
877 /// assert_eq!(iter.next(), None);
880 #[stable(feature = "rust1", since = "1.0.0")]
881 fn peekable(self) -> Peekable
<Self>
888 /// Creates an iterator that [`skip`]s elements based on a predicate.
890 /// [`skip`]: #method.skip
892 /// `skip_while()` takes a closure as an argument. It will call this
893 /// closure on each element of the iterator, and ignore elements
894 /// until it returns `false`.
896 /// After `false` is returned, `skip_while()`'s job is over, and the
897 /// rest of the elements are yielded.
904 /// let a = [-1i32, 0, 1];
906 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
908 /// assert_eq!(iter.next(), Some(&0));
909 /// assert_eq!(iter.next(), Some(&1));
910 /// assert_eq!(iter.next(), None);
913 /// Because the closure passed to `skip_while()` takes a reference, and many
914 /// iterators iterate over references, this leads to a possibly confusing
915 /// situation, where the type of the closure is a double reference:
918 /// let a = [-1, 0, 1];
920 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
922 /// assert_eq!(iter.next(), Some(&0));
923 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), None);
927 /// Stopping after an initial `false`:
930 /// let a = [-1, 0, 1, -2];
932 /// let mut iter = a.iter().skip_while(|x| **x < 0);
934 /// assert_eq!(iter.next(), Some(&0));
935 /// assert_eq!(iter.next(), Some(&1));
937 /// // while this would have been false, since we already got a false,
938 /// // skip_while() isn't used any more
939 /// assert_eq!(iter.next(), Some(&-2));
941 /// assert_eq!(iter.next(), None);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 fn skip_while
<P
>(self, predicate
: P
) -> SkipWhile
<Self, P
>
948 P
: FnMut(&Self::Item
) -> bool
,
950 SkipWhile
::new(self, predicate
)
953 /// Creates an iterator that yields elements based on a predicate.
955 /// `take_while()` takes a closure as an argument. It will call this
956 /// closure on each element of the iterator, and yield elements
957 /// while it returns `true`.
959 /// After `false` is returned, `take_while()`'s job is over, and the
960 /// rest of the elements are ignored.
967 /// let a = [-1i32, 0, 1];
969 /// let mut iter = a.iter().take_while(|x| x.is_negative());
971 /// assert_eq!(iter.next(), Some(&-1));
972 /// assert_eq!(iter.next(), None);
975 /// Because the closure passed to `take_while()` takes a reference, and many
976 /// iterators iterate over references, this leads to a possibly confusing
977 /// situation, where the type of the closure is a double reference:
980 /// let a = [-1, 0, 1];
982 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
984 /// assert_eq!(iter.next(), Some(&-1));
985 /// assert_eq!(iter.next(), None);
988 /// Stopping after an initial `false`:
991 /// let a = [-1, 0, 1, -2];
993 /// let mut iter = a.iter().take_while(|x| **x < 0);
995 /// assert_eq!(iter.next(), Some(&-1));
997 /// // We have more elements that are less than zero, but since we already
998 /// // got a false, take_while() isn't used any more
999 /// assert_eq!(iter.next(), None);
1002 /// Because `take_while()` needs to look at the value in order to see if it
1003 /// should be included or not, consuming iterators will see that it is
1007 /// let a = [1, 2, 3, 4];
1008 /// let mut iter = a.iter();
1010 /// let result: Vec<i32> = iter.by_ref()
1011 /// .take_while(|n| **n != 3)
1015 /// assert_eq!(result, &[1, 2]);
1017 /// let result: Vec<i32> = iter.cloned().collect();
1019 /// assert_eq!(result, &[4]);
1022 /// The `3` is no longer there, because it was consumed in order to see if
1023 /// the iteration should stop, but wasn't placed back into the iterator.
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 fn take_while
<P
>(self, predicate
: P
) -> TakeWhile
<Self, P
>
1029 P
: FnMut(&Self::Item
) -> bool
,
1031 TakeWhile
::new(self, predicate
)
1034 /// Creates an iterator that both yields elements based on a predicate and maps.
1036 /// `map_while()` takes a closure as an argument. It will call this
1037 /// closure on each element of the iterator, and yield elements
1038 /// while it returns [`Some(_)`][`Some`].
1045 /// #![feature(iter_map_while)]
1046 /// let a = [-1i32, 4, 0, 1];
1048 /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1050 /// assert_eq!(iter.next(), Some(-16));
1051 /// assert_eq!(iter.next(), Some(4));
1052 /// assert_eq!(iter.next(), None);
1055 /// Here's the same example, but with [`take_while`] and [`map`]:
1057 /// [`take_while`]: #method.take_while
1058 /// [`map`]: #method.map
1061 /// let a = [-1i32, 4, 0, 1];
1063 /// let mut iter = a.iter()
1064 /// .map(|x| 16i32.checked_div(*x))
1065 /// .take_while(|x| x.is_some())
1066 /// .map(|x| x.unwrap());
1068 /// assert_eq!(iter.next(), Some(-16));
1069 /// assert_eq!(iter.next(), Some(4));
1070 /// assert_eq!(iter.next(), None);
1073 /// Stopping after an initial [`None`]:
1076 /// #![feature(iter_map_while)]
1077 /// use std::convert::TryFrom;
1079 /// let a = [0, 1, 2, -3, 4, 5, -6];
1081 /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1082 /// let vec = iter.collect::<Vec<_>>();
1084 /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1085 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` entcountered.
1086 /// assert_eq!(vec, vec![0, 1, 2]);
1089 /// Because `map_while()` needs to look at the value in order to see if it
1090 /// should be included or not, consuming iterators will see that it is
1094 /// #![feature(iter_map_while)]
1095 /// use std::convert::TryFrom;
1097 /// let a = [1, 2, -3, 4];
1098 /// let mut iter = a.iter();
1100 /// let result: Vec<u32> = iter.by_ref()
1101 /// .map_while(|n| u32::try_from(*n).ok())
1104 /// assert_eq!(result, &[1, 2]);
1106 /// let result: Vec<i32> = iter.cloned().collect();
1108 /// assert_eq!(result, &[4]);
1111 /// The `-3` is no longer there, because it was consumed in order to see if
1112 /// the iteration should stop, but wasn't placed back into the iterator.
1114 /// Note that unlike [`take_while`] this iterator is **not** fused.
1115 /// It is also not specified what this iterator returns after the first` None` is returned.
1116 /// If you need fused iterator, use [`fuse`].
1118 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
1119 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1120 /// [`fuse`]: #method.fuse
1122 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1123 fn map_while
<B
, P
>(self, predicate
: P
) -> MapWhile
<Self, P
>
1126 P
: FnMut(Self::Item
) -> Option
<B
>,
1128 MapWhile
::new(self, predicate
)
1131 /// Creates an iterator that skips the first `n` elements.
1133 /// After they have been consumed, the rest of the elements are yielded.
1134 /// Rather than overriding this method directly, instead override the `nth` method.
1141 /// let a = [1, 2, 3];
1143 /// let mut iter = a.iter().skip(2);
1145 /// assert_eq!(iter.next(), Some(&3));
1146 /// assert_eq!(iter.next(), None);
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 fn skip(self, n
: usize) -> Skip
<Self>
1157 /// Creates an iterator that yields its first `n` elements.
1164 /// let a = [1, 2, 3];
1166 /// let mut iter = a.iter().take(2);
1168 /// assert_eq!(iter.next(), Some(&1));
1169 /// assert_eq!(iter.next(), Some(&2));
1170 /// assert_eq!(iter.next(), None);
1173 /// `take()` is often used with an infinite iterator, to make it finite:
1176 /// let mut iter = (0..).take(3);
1178 /// assert_eq!(iter.next(), Some(0));
1179 /// assert_eq!(iter.next(), Some(1));
1180 /// assert_eq!(iter.next(), Some(2));
1181 /// assert_eq!(iter.next(), None);
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 fn take(self, n
: usize) -> Take
<Self>
1192 /// An iterator adaptor similar to [`fold`] that holds internal state and
1193 /// produces a new iterator.
1195 /// [`fold`]: #method.fold
1197 /// `scan()` takes two arguments: an initial value which seeds the internal
1198 /// state, and a closure with two arguments, the first being a mutable
1199 /// reference to the internal state and the second an iterator element.
1200 /// The closure can assign to the internal state to share state between
1203 /// On iteration, the closure will be applied to each element of the
1204 /// iterator and the return value from the closure, an [`Option`], is
1205 /// yielded by the iterator.
1207 /// [`Option`]: ../../std/option/enum.Option.html
1214 /// let a = [1, 2, 3];
1216 /// let mut iter = a.iter().scan(1, |state, &x| {
1217 /// // each iteration, we'll multiply the state by the element
1218 /// *state = *state * x;
1220 /// // then, we'll yield the negation of the state
1224 /// assert_eq!(iter.next(), Some(-1));
1225 /// assert_eq!(iter.next(), Some(-2));
1226 /// assert_eq!(iter.next(), Some(-6));
1227 /// assert_eq!(iter.next(), None);
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 fn scan
<St
, B
, F
>(self, initial_state
: St
, f
: F
) -> Scan
<Self, St
, F
>
1234 F
: FnMut(&mut St
, Self::Item
) -> Option
<B
>,
1236 Scan
::new(self, initial_state
, f
)
1239 /// Creates an iterator that works like map, but flattens nested structure.
1241 /// The [`map`] adapter is very useful, but only when the closure
1242 /// argument produces values. If it produces an iterator instead, there's
1243 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1246 /// You can think of `flat_map(f)` as the semantic equivalent
1247 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1249 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1250 /// one item for each element, and `flat_map()`'s closure returns an
1251 /// iterator for each element.
1253 /// [`map`]: #method.map
1254 /// [`flatten`]: #method.flatten
1261 /// let words = ["alpha", "beta", "gamma"];
1263 /// // chars() returns an iterator
1264 /// let merged: String = words.iter()
1265 /// .flat_map(|s| s.chars())
1267 /// assert_eq!(merged, "alphabetagamma");
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 fn flat_map
<U
, F
>(self, f
: F
) -> FlatMap
<Self, U
, F
>
1275 F
: FnMut(Self::Item
) -> U
,
1277 FlatMap
::new(self, f
)
1280 /// Creates an iterator that flattens nested structure.
1282 /// This is useful when you have an iterator of iterators or an iterator of
1283 /// things that can be turned into iterators and you want to remove one
1284 /// level of indirection.
1291 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1292 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1293 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1296 /// Mapping and then flattening:
1299 /// let words = ["alpha", "beta", "gamma"];
1301 /// // chars() returns an iterator
1302 /// let merged: String = words.iter()
1303 /// .map(|s| s.chars())
1306 /// assert_eq!(merged, "alphabetagamma");
1309 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1310 /// in this case since it conveys intent more clearly:
1313 /// let words = ["alpha", "beta", "gamma"];
1315 /// // chars() returns an iterator
1316 /// let merged: String = words.iter()
1317 /// .flat_map(|s| s.chars())
1319 /// assert_eq!(merged, "alphabetagamma");
1322 /// Flattening once only removes one level of nesting:
1325 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1327 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1328 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1330 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1331 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1334 /// Here we see that `flatten()` does not perform a "deep" flatten.
1335 /// Instead, only one level of nesting is removed. That is, if you
1336 /// `flatten()` a three-dimensional array the result will be
1337 /// two-dimensional and not one-dimensional. To get a one-dimensional
1338 /// structure, you have to `flatten()` again.
1340 /// [`flat_map()`]: #method.flat_map
1342 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1343 fn flatten(self) -> Flatten
<Self>
1346 Self::Item
: IntoIterator
,
1351 /// Creates an iterator which ends after the first [`None`].
1353 /// After an iterator returns [`None`], future calls may or may not yield
1354 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1355 /// [`None`] is given, it will always return [`None`] forever.
1357 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1358 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1365 /// // an iterator which alternates between Some and None
1366 /// struct Alternate {
1370 /// impl Iterator for Alternate {
1371 /// type Item = i32;
1373 /// fn next(&mut self) -> Option<i32> {
1374 /// let val = self.state;
1375 /// self.state = self.state + 1;
1377 /// // if it's even, Some(i32), else None
1378 /// if val % 2 == 0 {
1386 /// let mut iter = Alternate { state: 0 };
1388 /// // we can see our iterator going back and forth
1389 /// assert_eq!(iter.next(), Some(0));
1390 /// assert_eq!(iter.next(), None);
1391 /// assert_eq!(iter.next(), Some(2));
1392 /// assert_eq!(iter.next(), None);
1394 /// // however, once we fuse it...
1395 /// let mut iter = iter.fuse();
1397 /// assert_eq!(iter.next(), Some(4));
1398 /// assert_eq!(iter.next(), None);
1400 /// // it will always return `None` after the first time.
1401 /// assert_eq!(iter.next(), None);
1402 /// assert_eq!(iter.next(), None);
1403 /// assert_eq!(iter.next(), None);
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 fn fuse(self) -> Fuse
<Self>
1414 /// Does something with each element of an iterator, passing the value on.
1416 /// When using iterators, you'll often chain several of them together.
1417 /// While working on such code, you might want to check out what's
1418 /// happening at various parts in the pipeline. To do that, insert
1419 /// a call to `inspect()`.
1421 /// It's more common for `inspect()` to be used as a debugging tool than to
1422 /// exist in your final code, but applications may find it useful in certain
1423 /// situations when errors need to be logged before being discarded.
1430 /// let a = [1, 4, 2, 3];
1432 /// // this iterator sequence is complex.
1433 /// let sum = a.iter()
1435 /// .filter(|x| x % 2 == 0)
1436 /// .fold(0, |sum, i| sum + i);
1438 /// println!("{}", sum);
1440 /// // let's add some inspect() calls to investigate what's happening
1441 /// let sum = a.iter()
1443 /// .inspect(|x| println!("about to filter: {}", x))
1444 /// .filter(|x| x % 2 == 0)
1445 /// .inspect(|x| println!("made it through filter: {}", x))
1446 /// .fold(0, |sum, i| sum + i);
1448 /// println!("{}", sum);
1451 /// This will print:
1455 /// about to filter: 1
1456 /// about to filter: 4
1457 /// made it through filter: 4
1458 /// about to filter: 2
1459 /// made it through filter: 2
1460 /// about to filter: 3
1464 /// Logging errors before discarding them:
1467 /// let lines = ["1", "2", "a"];
1469 /// let sum: i32 = lines
1471 /// .map(|line| line.parse::<i32>())
1472 /// .inspect(|num| {
1473 /// if let Err(ref e) = *num {
1474 /// println!("Parsing error: {}", e);
1477 /// .filter_map(Result::ok)
1480 /// println!("Sum: {}", sum);
1483 /// This will print:
1486 /// Parsing error: invalid digit found in string
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 fn inspect
<F
>(self, f
: F
) -> Inspect
<Self, F
>
1494 F
: FnMut(&Self::Item
),
1496 Inspect
::new(self, f
)
1499 /// Borrows an iterator, rather than consuming it.
1501 /// This is useful to allow applying iterator adaptors while still
1502 /// retaining ownership of the original iterator.
1509 /// let a = [1, 2, 3];
1511 /// let iter = a.iter();
1513 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1515 /// assert_eq!(sum, 6);
1517 /// // if we try to use iter again, it won't work. The following line
1518 /// // gives "error: use of moved value: `iter`
1519 /// // assert_eq!(iter.next(), None);
1521 /// // let's try that again
1522 /// let a = [1, 2, 3];
1524 /// let mut iter = a.iter();
1526 /// // instead, we add in a .by_ref()
1527 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1529 /// assert_eq!(sum, 3);
1531 /// // now this is just fine:
1532 /// assert_eq!(iter.next(), Some(&3));
1533 /// assert_eq!(iter.next(), None);
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 fn by_ref(&mut self) -> &mut Self
1543 /// Transforms an iterator into a collection.
1545 /// `collect()` can take anything iterable, and turn it into a relevant
1546 /// collection. This is one of the more powerful methods in the standard
1547 /// library, used in a variety of contexts.
1549 /// The most basic pattern in which `collect()` is used is to turn one
1550 /// collection into another. You take a collection, call [`iter`] on it,
1551 /// do a bunch of transformations, and then `collect()` at the end.
1553 /// One of the keys to `collect()`'s power is that many things you might
1554 /// not think of as 'collections' actually are. For example, a [`String`]
1555 /// is a collection of [`char`]s. And a collection of
1556 /// [`Result<T, E>`][`Result`] can be thought of as single
1557 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1559 /// Because `collect()` is so general, it can cause problems with type
1560 /// inference. As such, `collect()` is one of the few times you'll see
1561 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1562 /// helps the inference algorithm understand specifically which collection
1563 /// you're trying to collect into.
1570 /// let a = [1, 2, 3];
1572 /// let doubled: Vec<i32> = a.iter()
1573 /// .map(|&x| x * 2)
1576 /// assert_eq!(vec![2, 4, 6], doubled);
1579 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1580 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1582 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1585 /// use std::collections::VecDeque;
1587 /// let a = [1, 2, 3];
1589 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1591 /// assert_eq!(2, doubled[0]);
1592 /// assert_eq!(4, doubled[1]);
1593 /// assert_eq!(6, doubled[2]);
1596 /// Using the 'turbofish' instead of annotating `doubled`:
1599 /// let a = [1, 2, 3];
1601 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1603 /// assert_eq!(vec![2, 4, 6], doubled);
1606 /// Because `collect()` only cares about what you're collecting into, you can
1607 /// still use a partial type hint, `_`, with the turbofish:
1610 /// let a = [1, 2, 3];
1612 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1614 /// assert_eq!(vec![2, 4, 6], doubled);
1617 /// Using `collect()` to make a [`String`]:
1620 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1622 /// let hello: String = chars.iter()
1623 /// .map(|&x| x as u8)
1624 /// .map(|x| (x + 1) as char)
1627 /// assert_eq!("hello", hello);
1630 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1631 /// see if any of them failed:
1634 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1636 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1638 /// // gives us the first error
1639 /// assert_eq!(Err("nope"), result);
1641 /// let results = [Ok(1), Ok(3)];
1643 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1645 /// // gives us the list of answers
1646 /// assert_eq!(Ok(vec![1, 3]), result);
1649 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1650 /// [`String`]: ../../std/string/struct.String.html
1651 /// [`char`]: ../../std/primitive.char.html
1652 /// [`Result`]: ../../std/result/enum.Result.html
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1656 fn collect
<B
: FromIterator
<Self::Item
>>(self) -> B
1660 FromIterator
::from_iter(self)
1663 /// Consumes an iterator, creating two collections from it.
1665 /// The predicate passed to `partition()` can return `true`, or `false`.
1666 /// `partition()` returns a pair, all of the elements for which it returned
1667 /// `true`, and all of the elements for which it returned `false`.
1669 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1671 /// [`is_partitioned()`]: #method.is_partitioned
1672 /// [`partition_in_place()`]: #method.partition_in_place
1679 /// let a = [1, 2, 3];
1681 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1683 /// .partition(|&n| n % 2 == 0);
1685 /// assert_eq!(even, vec![2]);
1686 /// assert_eq!(odd, vec![1, 3]);
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 fn partition
<B
, F
>(self, f
: F
) -> (B
, B
)
1692 B
: Default
+ Extend
<Self::Item
>,
1693 F
: FnMut(&Self::Item
) -> bool
,
1696 fn extend
<'a
, T
, B
: Extend
<T
>>(
1697 mut f
: impl FnMut(&T
) -> bool
+ 'a
,
1700 ) -> impl FnMut(T
) + 'a
{
1703 left
.extend(Some(x
));
1705 right
.extend(Some(x
));
1710 let mut left
: B
= Default
::default();
1711 let mut right
: B
= Default
::default();
1713 self.for_each(extend(f
, &mut left
, &mut right
));
1718 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1719 /// such that all those that return `true` precede all those that return `false`.
1720 /// Returns the number of `true` elements found.
1722 /// The relative order of partitioned items is not maintained.
1724 /// See also [`is_partitioned()`] and [`partition()`].
1726 /// [`is_partitioned()`]: #method.is_partitioned
1727 /// [`partition()`]: #method.partition
1732 /// #![feature(iter_partition_in_place)]
1734 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1736 /// // Partition in-place between evens and odds
1737 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1739 /// assert_eq!(i, 3);
1740 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1741 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1743 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1744 fn partition_in_place
<'a
, T
: 'a
, P
>(mut self, ref mut predicate
: P
) -> usize
1746 Self: Sized
+ DoubleEndedIterator
<Item
= &'a
mut T
>,
1747 P
: FnMut(&T
) -> bool
,
1749 // FIXME: should we worry about the count overflowing? The only way to have more than
1750 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1752 // These closure "factory" functions exist to avoid genericity in `Self`.
1756 predicate
: &'a
mut impl FnMut(&T
) -> bool
,
1757 true_count
: &'a
mut usize,
1758 ) -> impl FnMut(&&mut T
) -> bool
+ 'a
{
1760 let p
= predicate(&**x
);
1761 *true_count
+= p
as usize;
1767 fn is_true
<T
>(predicate
: &mut impl FnMut(&T
) -> bool
) -> impl FnMut(&&mut T
) -> bool
+ '_
{
1768 move |x
| predicate(&**x
)
1771 // Repeatedly find the first `false` and swap it with the last `true`.
1772 let mut true_count
= 0;
1773 while let Some(head
) = self.find(is_false(predicate
, &mut true_count
)) {
1774 if let Some(tail
) = self.rfind(is_true(predicate
)) {
1775 crate::mem
::swap(head
, tail
);
1784 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1785 /// such that all those that return `true` precede all those that return `false`.
1787 /// See also [`partition()`] and [`partition_in_place()`].
1789 /// [`partition()`]: #method.partition
1790 /// [`partition_in_place()`]: #method.partition_in_place
1795 /// #![feature(iter_is_partitioned)]
1797 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1798 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1800 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1801 fn is_partitioned
<P
>(mut self, mut predicate
: P
) -> bool
1804 P
: FnMut(Self::Item
) -> bool
,
1806 // Either all items test `true`, or the first clause stops at `false`
1807 // and we check that there are no more `true` items after that.
1808 self.all(&mut predicate
) || !self.any(predicate
)
1811 /// An iterator method that applies a function as long as it returns
1812 /// successfully, producing a single, final value.
1814 /// `try_fold()` takes two arguments: an initial value, and a closure with
1815 /// two arguments: an 'accumulator', and an element. The closure either
1816 /// returns successfully, with the value that the accumulator should have
1817 /// for the next iteration, or it returns failure, with an error value that
1818 /// is propagated back to the caller immediately (short-circuiting).
1820 /// The initial value is the value the accumulator will have on the first
1821 /// call. If applying the closure succeeded against every element of the
1822 /// iterator, `try_fold()` returns the final accumulator as success.
1824 /// Folding is useful whenever you have a collection of something, and want
1825 /// to produce a single value from it.
1827 /// # Note to Implementors
1829 /// Most of the other (forward) methods have default implementations in
1830 /// terms of this one, so try to implement this explicitly if it can
1831 /// do something better than the default `for` loop implementation.
1833 /// In particular, try to have this call `try_fold()` on the internal parts
1834 /// from which this iterator is composed. If multiple calls are needed,
1835 /// the `?` operator may be convenient for chaining the accumulator value
1836 /// along, but beware any invariants that need to be upheld before those
1837 /// early returns. This is a `&mut self` method, so iteration needs to be
1838 /// resumable after hitting an error here.
1845 /// let a = [1, 2, 3];
1847 /// // the checked sum of all of the elements of the array
1848 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1850 /// assert_eq!(sum, Some(6));
1853 /// Short-circuiting:
1856 /// let a = [10, 20, 30, 100, 40, 50];
1857 /// let mut it = a.iter();
1859 /// // This sum overflows when adding the 100 element
1860 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1861 /// assert_eq!(sum, None);
1863 /// // Because it short-circuited, the remaining elements are still
1864 /// // available through the iterator.
1865 /// assert_eq!(it.len(), 2);
1866 /// assert_eq!(it.next(), Some(&40));
1869 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1870 fn try_fold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
1873 F
: FnMut(B
, Self::Item
) -> R
,
1876 let mut accum
= init
;
1877 while let Some(x
) = self.next() {
1878 accum
= f(accum
, x
)?
;
1883 /// An iterator method that applies a fallible function to each item in the
1884 /// iterator, stopping at the first error and returning that error.
1886 /// This can also be thought of as the fallible form of [`for_each()`]
1887 /// or as the stateless version of [`try_fold()`].
1889 /// [`for_each()`]: #method.for_each
1890 /// [`try_fold()`]: #method.try_fold
1895 /// use std::fs::rename;
1896 /// use std::io::{stdout, Write};
1897 /// use std::path::Path;
1899 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1901 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1902 /// assert!(res.is_ok());
1904 /// let mut it = data.iter().cloned();
1905 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1906 /// assert!(res.is_err());
1907 /// // It short-circuited, so the remaining items are still in the iterator:
1908 /// assert_eq!(it.next(), Some("stale_bread.json"));
1911 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1912 fn try_for_each
<F
, R
>(&mut self, f
: F
) -> R
1915 F
: FnMut(Self::Item
) -> R
,
1919 fn call
<T
, R
>(mut f
: impl FnMut(T
) -> R
) -> impl FnMut((), T
) -> R
{
1923 self.try_fold((), call(f
))
1926 /// An iterator method that applies a function, producing a single, final value.
1928 /// `fold()` takes two arguments: an initial value, and a closure with two
1929 /// arguments: an 'accumulator', and an element. The closure returns the value that
1930 /// the accumulator should have for the next iteration.
1932 /// The initial value is the value the accumulator will have on the first
1935 /// After applying this closure to every element of the iterator, `fold()`
1936 /// returns the accumulator.
1938 /// This operation is sometimes called 'reduce' or 'inject'.
1940 /// Folding is useful whenever you have a collection of something, and want
1941 /// to produce a single value from it.
1943 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1944 /// may not terminate for infinite iterators, even on traits for which a
1945 /// result is determinable in finite time.
1952 /// let a = [1, 2, 3];
1954 /// // the sum of all of the elements of the array
1955 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1957 /// assert_eq!(sum, 6);
1960 /// Let's walk through each step of the iteration here:
1962 /// | element | acc | x | result |
1963 /// |---------|-----|---|--------|
1965 /// | 1 | 0 | 1 | 1 |
1966 /// | 2 | 1 | 2 | 3 |
1967 /// | 3 | 3 | 3 | 6 |
1969 /// And so, our final result, `6`.
1971 /// It's common for people who haven't used iterators a lot to
1972 /// use a `for` loop with a list of things to build up a result. Those
1973 /// can be turned into `fold()`s:
1975 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1978 /// let numbers = [1, 2, 3, 4, 5];
1980 /// let mut result = 0;
1983 /// for i in &numbers {
1984 /// result = result + i;
1988 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1990 /// // they're the same
1991 /// assert_eq!(result, result2);
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 fn fold
<B
, F
>(mut self, init
: B
, f
: F
) -> B
1998 F
: FnMut(B
, Self::Item
) -> B
,
2001 fn ok
<B
, T
>(mut f
: impl FnMut(B
, T
) -> B
) -> impl FnMut(B
, T
) -> Result
<B
, !> {
2002 move |acc
, x
| Ok(f(acc
, x
))
2005 self.try_fold(init
, ok(f
)).unwrap()
2008 /// The same as [`fold()`](#method.fold), but uses the first element in the
2009 /// iterator as the initial value, folding every subsequent element into it.
2010 /// If the iterator is empty, return `None`; otherwise, return the result
2015 /// Find the maximum value:
2018 /// #![feature(iterator_fold_self)]
2020 /// fn find_max<I>(iter: I) -> Option<I::Item>
2021 /// where I: Iterator,
2024 /// iter.fold_first(|a, b| {
2025 /// if a >= b { a } else { b }
2028 /// let a = [10, 20, 5, -23, 0];
2029 /// let b: [u32; 0] = [];
2031 /// assert_eq!(find_max(a.iter()), Some(&20));
2032 /// assert_eq!(find_max(b.iter()), None);
2035 #[unstable(feature = "iterator_fold_self", issue = "68125")]
2036 fn fold_first
<F
>(mut self, f
: F
) -> Option
<Self::Item
>
2039 F
: FnMut(Self::Item
, Self::Item
) -> Self::Item
,
2041 let first
= self.next()?
;
2042 Some(self.fold(first
, f
))
2045 /// Tests if every element of the iterator matches a predicate.
2047 /// `all()` takes a closure that returns `true` or `false`. It applies
2048 /// this closure to each element of the iterator, and if they all return
2049 /// `true`, then so does `all()`. If any of them return `false`, it
2050 /// returns `false`.
2052 /// `all()` is short-circuiting; in other words, it will stop processing
2053 /// as soon as it finds a `false`, given that no matter what else happens,
2054 /// the result will also be `false`.
2056 /// An empty iterator returns `true`.
2063 /// let a = [1, 2, 3];
2065 /// assert!(a.iter().all(|&x| x > 0));
2067 /// assert!(!a.iter().all(|&x| x > 2));
2070 /// Stopping at the first `false`:
2073 /// let a = [1, 2, 3];
2075 /// let mut iter = a.iter();
2077 /// assert!(!iter.all(|&x| x != 2));
2079 /// // we can still use `iter`, as there are more elements.
2080 /// assert_eq!(iter.next(), Some(&3));
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 fn all
<F
>(&mut self, f
: F
) -> bool
2087 F
: FnMut(Self::Item
) -> bool
,
2090 fn check
<T
>(mut f
: impl FnMut(T
) -> bool
) -> impl FnMut((), T
) -> LoopState
<(), ()> {
2092 if f(x
) { LoopState::Continue(()) }
else { LoopState::Break(()) }
2095 self.try_fold((), check(f
)) == LoopState
::Continue(())
2098 /// Tests if any element of the iterator matches a predicate.
2100 /// `any()` takes a closure that returns `true` or `false`. It applies
2101 /// this closure to each element of the iterator, and if any of them return
2102 /// `true`, then so does `any()`. If they all return `false`, it
2103 /// returns `false`.
2105 /// `any()` is short-circuiting; in other words, it will stop processing
2106 /// as soon as it finds a `true`, given that no matter what else happens,
2107 /// the result will also be `true`.
2109 /// An empty iterator returns `false`.
2116 /// let a = [1, 2, 3];
2118 /// assert!(a.iter().any(|&x| x > 0));
2120 /// assert!(!a.iter().any(|&x| x > 5));
2123 /// Stopping at the first `true`:
2126 /// let a = [1, 2, 3];
2128 /// let mut iter = a.iter();
2130 /// assert!(iter.any(|&x| x != 2));
2132 /// // we can still use `iter`, as there are more elements.
2133 /// assert_eq!(iter.next(), Some(&2));
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 fn any
<F
>(&mut self, f
: F
) -> bool
2140 F
: FnMut(Self::Item
) -> bool
,
2143 fn check
<T
>(mut f
: impl FnMut(T
) -> bool
) -> impl FnMut((), T
) -> LoopState
<(), ()> {
2145 if f(x
) { LoopState::Break(()) }
else { LoopState::Continue(()) }
2149 self.try_fold((), check(f
)) == LoopState
::Break(())
2152 /// Searches for an element of an iterator that satisfies a predicate.
2154 /// `find()` takes a closure that returns `true` or `false`. It applies
2155 /// this closure to each element of the iterator, and if any of them return
2156 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2157 /// `false`, it returns [`None`].
2159 /// `find()` is short-circuiting; in other words, it will stop processing
2160 /// as soon as the closure returns `true`.
2162 /// Because `find()` takes a reference, and many iterators iterate over
2163 /// references, this leads to a possibly confusing situation where the
2164 /// argument is a double reference. You can see this effect in the
2165 /// examples below, with `&&x`.
2167 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
2168 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2175 /// let a = [1, 2, 3];
2177 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2179 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2182 /// Stopping at the first `true`:
2185 /// let a = [1, 2, 3];
2187 /// let mut iter = a.iter();
2189 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2191 /// // we can still use `iter`, as there are more elements.
2192 /// assert_eq!(iter.next(), Some(&3));
2195 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 fn find
<P
>(&mut self, predicate
: P
) -> Option
<Self::Item
>
2201 P
: FnMut(&Self::Item
) -> bool
,
2205 mut predicate
: impl FnMut(&T
) -> bool
,
2206 ) -> impl FnMut((), T
) -> LoopState
<(), T
> {
2208 if predicate(&x
) { LoopState::Break(x) }
else { LoopState::Continue(()) }
2212 self.try_fold((), check(predicate
)).break_value()
2215 /// Applies function to the elements of iterator and returns
2216 /// the first non-none result.
2218 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2224 /// let a = ["lol", "NaN", "2", "5"];
2226 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2228 /// assert_eq!(first_number, Some(2));
2231 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2232 fn find_map
<B
, F
>(&mut self, f
: F
) -> Option
<B
>
2235 F
: FnMut(Self::Item
) -> Option
<B
>,
2238 fn check
<T
, B
>(mut f
: impl FnMut(T
) -> Option
<B
>) -> impl FnMut((), T
) -> LoopState
<(), B
> {
2239 move |(), x
| match f(x
) {
2240 Some(x
) => LoopState
::Break(x
),
2241 None
=> LoopState
::Continue(()),
2245 self.try_fold((), check(f
)).break_value()
2248 /// Applies function to the elements of iterator and returns
2249 /// the first non-none result or the first error.
2254 /// #![feature(try_find)]
2256 /// let a = ["1", "2", "lol", "NaN", "5"];
2258 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2259 /// Ok(s.parse::<i32>()? == search)
2262 /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2263 /// assert_eq!(result, Ok(Some(&"2")));
2265 /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2266 /// assert!(result.is_err());
2269 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2270 fn try_find
<F
, E
, R
>(&mut self, mut f
: F
) -> Result
<Option
<Self::Item
>, E
>
2273 F
: FnMut(&Self::Item
) -> R
,
2274 R
: Try
<Ok
= bool
, Error
= E
>,
2276 self.try_for_each(move |x
| match f(&x
).into_result() {
2277 Ok(false) => LoopState
::Continue(()),
2278 Ok(true) => LoopState
::Break(Ok(x
)),
2279 Err(x
) => LoopState
::Break(Err(x
)),
2285 /// Searches for an element in an iterator, returning its index.
2287 /// `position()` takes a closure that returns `true` or `false`. It applies
2288 /// this closure to each element of the iterator, and if one of them
2289 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2290 /// them return `false`, it returns [`None`].
2292 /// `position()` is short-circuiting; in other words, it will stop
2293 /// processing as soon as it finds a `true`.
2295 /// # Overflow Behavior
2297 /// The method does no guarding against overflows, so if there are more
2298 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2299 /// result or panics. If debug assertions are enabled, a panic is
2304 /// This function might panic if the iterator has more than `usize::MAX`
2305 /// non-matching elements.
2307 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2308 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2309 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
2316 /// let a = [1, 2, 3];
2318 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2320 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2323 /// Stopping at the first `true`:
2326 /// let a = [1, 2, 3, 4];
2328 /// let mut iter = a.iter();
2330 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2332 /// // we can still use `iter`, as there are more elements.
2333 /// assert_eq!(iter.next(), Some(&3));
2335 /// // The returned index depends on iterator state
2336 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 fn position
<P
>(&mut self, predicate
: P
) -> Option
<usize>
2344 P
: FnMut(Self::Item
) -> bool
,
2348 mut predicate
: impl FnMut(T
) -> bool
,
2349 ) -> impl FnMut(usize, T
) -> LoopState
<usize, usize> {
2350 // The addition might panic on overflow
2352 if predicate(x
) { LoopState::Break(i) }
else { LoopState::Continue(Add::add(i, 1)) }
2356 self.try_fold(0, check(predicate
)).break_value()
2359 /// Searches for an element in an iterator from the right, returning its
2362 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2363 /// this closure to each element of the iterator, starting from the end,
2364 /// and if one of them returns `true`, then `rposition()` returns
2365 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2367 /// `rposition()` is short-circuiting; in other words, it will stop
2368 /// processing as soon as it finds a `true`.
2370 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2371 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2378 /// let a = [1, 2, 3];
2380 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2382 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2385 /// Stopping at the first `true`:
2388 /// let a = [1, 2, 3];
2390 /// let mut iter = a.iter();
2392 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2394 /// // we can still use `iter`, as there are more elements.
2395 /// assert_eq!(iter.next(), Some(&1));
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 fn rposition
<P
>(&mut self, predicate
: P
) -> Option
<usize>
2401 P
: FnMut(Self::Item
) -> bool
,
2402 Self: Sized
+ ExactSizeIterator
+ DoubleEndedIterator
,
2404 // No need for an overflow check here, because `ExactSizeIterator`
2405 // implies that the number of elements fits into a `usize`.
2408 mut predicate
: impl FnMut(T
) -> bool
,
2409 ) -> impl FnMut(usize, T
) -> LoopState
<usize, usize> {
2412 if predicate(x
) { LoopState::Break(i) }
else { LoopState::Continue(i) }
2417 self.try_rfold(n
, check(predicate
)).break_value()
2420 /// Returns the maximum element of an iterator.
2422 /// If several elements are equally maximum, the last element is
2423 /// returned. If the iterator is empty, [`None`] is returned.
2425 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2432 /// let a = [1, 2, 3];
2433 /// let b: Vec<u32> = Vec::new();
2435 /// assert_eq!(a.iter().max(), Some(&3));
2436 /// assert_eq!(b.iter().max(), None);
2439 #[stable(feature = "rust1", since = "1.0.0")]
2440 fn max(self) -> Option
<Self::Item
>
2445 self.max_by(Ord
::cmp
)
2448 /// Returns the minimum element of an iterator.
2450 /// If several elements are equally minimum, the first element is
2451 /// returned. If the iterator is empty, [`None`] is returned.
2453 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2460 /// let a = [1, 2, 3];
2461 /// let b: Vec<u32> = Vec::new();
2463 /// assert_eq!(a.iter().min(), Some(&1));
2464 /// assert_eq!(b.iter().min(), None);
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 fn min(self) -> Option
<Self::Item
>
2473 self.min_by(Ord
::cmp
)
2476 /// Returns the element that gives the maximum value from the
2477 /// specified function.
2479 /// If several elements are equally maximum, the last element is
2480 /// returned. If the iterator is empty, [`None`] is returned.
2482 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2487 /// let a = [-3_i32, 0, 1, 5, -10];
2488 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2491 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2492 fn max_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
2495 F
: FnMut(&Self::Item
) -> B
,
2498 fn key
<T
, B
>(mut f
: impl FnMut(&T
) -> B
) -> impl FnMut(T
) -> (B
, T
) {
2503 fn compare
<T
, B
: Ord
>((x_p
, _
): &(B
, T
), (y_p
, _
): &(B
, T
)) -> Ordering
{
2507 let (_
, x
) = self.map(key(f
)).max_by(compare
)?
;
2511 /// Returns the element that gives the maximum value with respect to the
2512 /// specified comparison function.
2514 /// If several elements are equally maximum, the last element is
2515 /// returned. If the iterator is empty, [`None`] is returned.
2517 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2522 /// let a = [-3_i32, 0, 1, 5, -10];
2523 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2526 #[stable(feature = "iter_max_by", since = "1.15.0")]
2527 fn max_by
<F
>(self, compare
: F
) -> Option
<Self::Item
>
2530 F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2533 fn fold
<T
>(mut compare
: impl FnMut(&T
, &T
) -> Ordering
) -> impl FnMut(T
, T
) -> T
{
2534 move |x
, y
| cmp
::max_by(x
, y
, &mut compare
)
2537 self.fold_first(fold(compare
))
2540 /// Returns the element that gives the minimum value from the
2541 /// specified function.
2543 /// If several elements are equally minimum, the first element is
2544 /// returned. If the iterator is empty, [`None`] is returned.
2546 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2551 /// let a = [-3_i32, 0, 1, 5, -10];
2552 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2555 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2556 fn min_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
2559 F
: FnMut(&Self::Item
) -> B
,
2562 fn key
<T
, B
>(mut f
: impl FnMut(&T
) -> B
) -> impl FnMut(T
) -> (B
, T
) {
2567 fn compare
<T
, B
: Ord
>((x_p
, _
): &(B
, T
), (y_p
, _
): &(B
, T
)) -> Ordering
{
2571 let (_
, x
) = self.map(key(f
)).min_by(compare
)?
;
2575 /// Returns the element that gives the minimum value with respect to the
2576 /// specified comparison function.
2578 /// If several elements are equally minimum, the first element is
2579 /// returned. If the iterator is empty, [`None`] is returned.
2581 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2586 /// let a = [-3_i32, 0, 1, 5, -10];
2587 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2590 #[stable(feature = "iter_min_by", since = "1.15.0")]
2591 fn min_by
<F
>(self, compare
: F
) -> Option
<Self::Item
>
2594 F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2597 fn fold
<T
>(mut compare
: impl FnMut(&T
, &T
) -> Ordering
) -> impl FnMut(T
, T
) -> T
{
2598 move |x
, y
| cmp
::min_by(x
, y
, &mut compare
)
2601 self.fold_first(fold(compare
))
2604 /// Reverses an iterator's direction.
2606 /// Usually, iterators iterate from left to right. After using `rev()`,
2607 /// an iterator will instead iterate from right to left.
2609 /// This is only possible if the iterator has an end, so `rev()` only
2610 /// works on [`DoubleEndedIterator`]s.
2612 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2617 /// let a = [1, 2, 3];
2619 /// let mut iter = a.iter().rev();
2621 /// assert_eq!(iter.next(), Some(&3));
2622 /// assert_eq!(iter.next(), Some(&2));
2623 /// assert_eq!(iter.next(), Some(&1));
2625 /// assert_eq!(iter.next(), None);
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 fn rev(self) -> Rev
<Self>
2631 Self: Sized
+ DoubleEndedIterator
,
2636 /// Converts an iterator of pairs into a pair of containers.
2638 /// `unzip()` consumes an entire iterator of pairs, producing two
2639 /// collections: one from the left elements of the pairs, and one
2640 /// from the right elements.
2642 /// This function is, in some sense, the opposite of [`zip`].
2644 /// [`zip`]: #method.zip
2651 /// let a = [(1, 2), (3, 4)];
2653 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2655 /// assert_eq!(left, [1, 3]);
2656 /// assert_eq!(right, [2, 4]);
2658 #[stable(feature = "rust1", since = "1.0.0")]
2659 fn unzip
<A
, B
, FromA
, FromB
>(self) -> (FromA
, FromB
)
2661 FromA
: Default
+ Extend
<A
>,
2662 FromB
: Default
+ Extend
<B
>,
2663 Self: Sized
+ Iterator
<Item
= (A
, B
)>,
2665 fn extend
<'a
, A
, B
>(
2666 ts
: &'a
mut impl Extend
<A
>,
2667 us
: &'a
mut impl Extend
<B
>,
2668 ) -> impl FnMut((A
, B
)) + 'a
{
2675 let mut ts
: FromA
= Default
::default();
2676 let mut us
: FromB
= Default
::default();
2678 self.for_each(extend(&mut ts
, &mut us
));
2683 /// Creates an iterator which copies all of its elements.
2685 /// This is useful when you have an iterator over `&T`, but you need an
2686 /// iterator over `T`.
2693 /// let a = [1, 2, 3];
2695 /// let v_cloned: Vec<_> = a.iter().copied().collect();
2697 /// // copied is the same as .map(|&x| x)
2698 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2700 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2701 /// assert_eq!(v_map, vec![1, 2, 3]);
2703 #[stable(feature = "iter_copied", since = "1.36.0")]
2704 fn copied
<'a
, T
: 'a
>(self) -> Copied
<Self>
2706 Self: Sized
+ Iterator
<Item
= &'a T
>,
2712 /// Creates an iterator which [`clone`]s all of its elements.
2714 /// This is useful when you have an iterator over `&T`, but you need an
2715 /// iterator over `T`.
2717 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2724 /// let a = [1, 2, 3];
2726 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2728 /// // cloned is the same as .map(|&x| x), for integers
2729 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2731 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2732 /// assert_eq!(v_map, vec![1, 2, 3]);
2734 #[stable(feature = "rust1", since = "1.0.0")]
2735 fn cloned
<'a
, T
: 'a
>(self) -> Cloned
<Self>
2737 Self: Sized
+ Iterator
<Item
= &'a T
>,
2743 /// Repeats an iterator endlessly.
2745 /// Instead of stopping at [`None`], the iterator will instead start again,
2746 /// from the beginning. After iterating again, it will start at the
2747 /// beginning again. And again. And again. Forever.
2749 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2756 /// let a = [1, 2, 3];
2758 /// let mut it = a.iter().cycle();
2760 /// assert_eq!(it.next(), Some(&1));
2761 /// assert_eq!(it.next(), Some(&2));
2762 /// assert_eq!(it.next(), Some(&3));
2763 /// assert_eq!(it.next(), Some(&1));
2764 /// assert_eq!(it.next(), Some(&2));
2765 /// assert_eq!(it.next(), Some(&3));
2766 /// assert_eq!(it.next(), Some(&1));
2768 #[stable(feature = "rust1", since = "1.0.0")]
2770 fn cycle(self) -> Cycle
<Self>
2772 Self: Sized
+ Clone
,
2777 /// Sums the elements of an iterator.
2779 /// Takes each element, adds them together, and returns the result.
2781 /// An empty iterator returns the zero value of the type.
2785 /// When calling `sum()` and a primitive integer type is being returned, this
2786 /// method will panic if the computation overflows and debug assertions are
2794 /// let a = [1, 2, 3];
2795 /// let sum: i32 = a.iter().sum();
2797 /// assert_eq!(sum, 6);
2799 #[stable(feature = "iter_arith", since = "1.11.0")]
2800 fn sum
<S
>(self) -> S
2808 /// Iterates over the entire iterator, multiplying all the elements
2810 /// An empty iterator returns the one value of the type.
2814 /// When calling `product()` and a primitive integer type is being returned,
2815 /// method will panic if the computation overflows and debug assertions are
2821 /// fn factorial(n: u32) -> u32 {
2822 /// (1..=n).product()
2824 /// assert_eq!(factorial(0), 1);
2825 /// assert_eq!(factorial(1), 1);
2826 /// assert_eq!(factorial(5), 120);
2828 #[stable(feature = "iter_arith", since = "1.11.0")]
2829 fn product
<P
>(self) -> P
2832 P
: Product
<Self::Item
>,
2834 Product
::product(self)
2837 /// Lexicographically compares the elements of this `Iterator` with those
2843 /// use std::cmp::Ordering;
2845 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2846 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2847 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2849 #[stable(feature = "iter_order", since = "1.5.0")]
2850 fn cmp
<I
>(self, other
: I
) -> Ordering
2852 I
: IntoIterator
<Item
= Self::Item
>,
2856 self.cmp_by(other
, |x
, y
| x
.cmp(&y
))
2859 /// Lexicographically compares the elements of this `Iterator` with those
2860 /// of another with respect to the specified comparison function.
2867 /// #![feature(iter_order_by)]
2869 /// use std::cmp::Ordering;
2871 /// let xs = [1, 2, 3, 4];
2872 /// let ys = [1, 4, 9, 16];
2874 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2875 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2876 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2878 #[unstable(feature = "iter_order_by", issue = "64295")]
2879 fn cmp_by
<I
, F
>(mut self, other
: I
, mut cmp
: F
) -> Ordering
2883 F
: FnMut(Self::Item
, I
::Item
) -> Ordering
,
2885 let mut other
= other
.into_iter();
2888 let x
= match self.next() {
2890 if other
.next().is_none() {
2891 return Ordering
::Equal
;
2893 return Ordering
::Less
;
2899 let y
= match other
.next() {
2900 None
=> return Ordering
::Greater
,
2905 Ordering
::Equal
=> (),
2906 non_eq
=> return non_eq
,
2911 /// Lexicographically compares the elements of this `Iterator` with those
2917 /// use std::cmp::Ordering;
2919 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2920 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2921 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2923 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2925 #[stable(feature = "iter_order", since = "1.5.0")]
2926 fn partial_cmp
<I
>(self, other
: I
) -> Option
<Ordering
>
2929 Self::Item
: PartialOrd
<I
::Item
>,
2932 self.partial_cmp_by(other
, |x
, y
| x
.partial_cmp(&y
))
2935 /// Lexicographically compares the elements of this `Iterator` with those
2936 /// of another with respect to the specified comparison function.
2943 /// #![feature(iter_order_by)]
2945 /// use std::cmp::Ordering;
2947 /// let xs = [1.0, 2.0, 3.0, 4.0];
2948 /// let ys = [1.0, 4.0, 9.0, 16.0];
2951 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2952 /// Some(Ordering::Less)
2955 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2956 /// Some(Ordering::Equal)
2959 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2960 /// Some(Ordering::Greater)
2963 #[unstable(feature = "iter_order_by", issue = "64295")]
2964 fn partial_cmp_by
<I
, F
>(mut self, other
: I
, mut partial_cmp
: F
) -> Option
<Ordering
>
2968 F
: FnMut(Self::Item
, I
::Item
) -> Option
<Ordering
>,
2970 let mut other
= other
.into_iter();
2973 let x
= match self.next() {
2975 if other
.next().is_none() {
2976 return Some(Ordering
::Equal
);
2978 return Some(Ordering
::Less
);
2984 let y
= match other
.next() {
2985 None
=> return Some(Ordering
::Greater
),
2989 match partial_cmp(x
, y
) {
2990 Some(Ordering
::Equal
) => (),
2991 non_eq
=> return non_eq
,
2996 /// Determines if the elements of this `Iterator` are equal to those of
3002 /// assert_eq!([1].iter().eq([1].iter()), true);
3003 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3005 #[stable(feature = "iter_order", since = "1.5.0")]
3006 fn eq
<I
>(self, other
: I
) -> bool
3009 Self::Item
: PartialEq
<I
::Item
>,
3012 self.eq_by(other
, |x
, y
| x
== y
)
3015 /// Determines if the elements of this `Iterator` are equal to those of
3016 /// another with respect to the specified equality function.
3023 /// #![feature(iter_order_by)]
3025 /// let xs = [1, 2, 3, 4];
3026 /// let ys = [1, 4, 9, 16];
3028 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3030 #[unstable(feature = "iter_order_by", issue = "64295")]
3031 fn eq_by
<I
, F
>(mut self, other
: I
, mut eq
: F
) -> bool
3035 F
: FnMut(Self::Item
, I
::Item
) -> bool
,
3037 let mut other
= other
.into_iter();
3040 let x
= match self.next() {
3041 None
=> return other
.next().is_none(),
3045 let y
= match other
.next() {
3046 None
=> return false,
3056 /// Determines if the elements of this `Iterator` are unequal to those of
3062 /// assert_eq!([1].iter().ne([1].iter()), false);
3063 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3065 #[stable(feature = "iter_order", since = "1.5.0")]
3066 fn ne
<I
>(self, other
: I
) -> bool
3069 Self::Item
: PartialEq
<I
::Item
>,
3075 /// Determines if the elements of this `Iterator` are lexicographically
3076 /// less than those of another.
3081 /// assert_eq!([1].iter().lt([1].iter()), false);
3082 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3083 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3085 #[stable(feature = "iter_order", since = "1.5.0")]
3086 fn lt
<I
>(self, other
: I
) -> bool
3089 Self::Item
: PartialOrd
<I
::Item
>,
3092 self.partial_cmp(other
) == Some(Ordering
::Less
)
3095 /// Determines if the elements of this `Iterator` are lexicographically
3096 /// less or equal to those of another.
3101 /// assert_eq!([1].iter().le([1].iter()), true);
3102 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3103 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3105 #[stable(feature = "iter_order", since = "1.5.0")]
3106 fn le
<I
>(self, other
: I
) -> bool
3109 Self::Item
: PartialOrd
<I
::Item
>,
3112 matches
!(self.partial_cmp(other
), Some(Ordering
::Less
| Ordering
::Equal
))
3115 /// Determines if the elements of this `Iterator` are lexicographically
3116 /// greater than those of another.
3121 /// assert_eq!([1].iter().gt([1].iter()), false);
3122 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3123 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3125 #[stable(feature = "iter_order", since = "1.5.0")]
3126 fn gt
<I
>(self, other
: I
) -> bool
3129 Self::Item
: PartialOrd
<I
::Item
>,
3132 self.partial_cmp(other
) == Some(Ordering
::Greater
)
3135 /// Determines if the elements of this `Iterator` are lexicographically
3136 /// greater than or equal to those of another.
3141 /// assert_eq!([1].iter().ge([1].iter()), true);
3142 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3143 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3145 #[stable(feature = "iter_order", since = "1.5.0")]
3146 fn ge
<I
>(self, other
: I
) -> bool
3149 Self::Item
: PartialOrd
<I
::Item
>,
3152 matches
!(self.partial_cmp(other
), Some(Ordering
::Greater
| Ordering
::Equal
))
3155 /// Checks if the elements of this iterator are sorted.
3157 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3158 /// iterator yields exactly zero or one element, `true` is returned.
3160 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3161 /// implies that this function returns `false` if any two consecutive items are not
3167 /// #![feature(is_sorted)]
3169 /// assert!([1, 2, 2, 9].iter().is_sorted());
3170 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3171 /// assert!([0].iter().is_sorted());
3172 /// assert!(std::iter::empty::<i32>().is_sorted());
3173 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3176 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3177 fn is_sorted(self) -> bool
3180 Self::Item
: PartialOrd
,
3182 self.is_sorted_by(PartialOrd
::partial_cmp
)
3185 /// Checks if the elements of this iterator are sorted using the given comparator function.
3187 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3188 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3189 /// [`is_sorted`]; see its documentation for more information.
3194 /// #![feature(is_sorted)]
3196 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3197 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3198 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3199 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3200 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3203 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3204 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3205 fn is_sorted_by
<F
>(mut self, mut compare
: F
) -> bool
3208 F
: FnMut(&Self::Item
, &Self::Item
) -> Option
<Ordering
>,
3210 let mut last
= match self.next() {
3212 None
=> return true,
3215 while let Some(curr
) = self.next() {
3216 if let Some(Ordering
::Greater
) | None
= compare(&last
, &curr
) {
3225 /// Checks if the elements of this iterator are sorted using the given key extraction
3228 /// Instead of comparing the iterator's elements directly, this function compares the keys of
3229 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3230 /// its documentation for more information.
3232 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3237 /// #![feature(is_sorted)]
3239 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3240 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3243 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3244 fn is_sorted_by_key
<F
, K
>(self, f
: F
) -> bool
3247 F
: FnMut(Self::Item
) -> K
,
3250 self.map(f
).is_sorted()
3254 #[stable(feature = "rust1", since = "1.0.0")]
3255 impl<I
: Iterator
+ ?Sized
> Iterator
for &mut I
{
3256 type Item
= I
::Item
;
3257 fn next(&mut self) -> Option
<I
::Item
> {
3260 fn size_hint(&self) -> (usize, Option
<usize>) {
3261 (**self).size_hint()
3263 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {