1 use crate::cmp
::{self, Ordering}
;
2 use crate::ops
::{Add, Try}
;
4 use super::super::LoopState
;
5 use super::super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse}
;
6 use super::super::{Flatten, FlatMap}
;
7 use super::super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev}
;
8 use super::super::{Zip, Sum, Product, FromIterator}
;
10 fn _assert_is_object_safe(_
: &dyn Iterator
<Item
=()>) {}
12 /// An interface for dealing with iterators.
14 /// This is the main iterator trait. For more about the concept of iterators
15 /// generally, please see the [module-level documentation]. In particular, you
16 /// may want to know how to [implement `Iterator`][impl].
18 /// [module-level documentation]: index.html
19 /// [impl]: index.html#implementing-iterator
20 #[stable(feature = "rust1", since = "1.0.0")]
21 #[rustc_on_unimplemented(
23 _Self
="[std::ops::Range<Idx>; 1]",
24 label
="if you meant to iterate between two values, remove the square brackets",
25 note
="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
26 without the brackets: `start..end`"
29 _Self
="[std::ops::RangeFrom<Idx>; 1]",
30 label
="if you meant to iterate from a value onwards, remove the square brackets",
31 note
="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
32 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
33 unbounded iterator will run forever unless you `break` or `return` from within the \
37 _Self
="[std::ops::RangeTo<Idx>; 1]",
38 label
="if you meant to iterate until a value, remove the square brackets and add a \
40 note
="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
41 `Range` without the brackets: `0..end`"
44 _Self
="[std::ops::RangeInclusive<Idx>; 1]",
45 label
="if you meant to iterate between two values, remove the square brackets",
46 note
="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
47 `RangeInclusive` without the brackets: `start..=end`"
50 _Self
="[std::ops::RangeToInclusive<Idx>; 1]",
51 label
="if you meant to iterate until a value (including it), remove the square brackets \
52 and add a starting value",
53 note
="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
54 bounded `RangeInclusive` without the brackets: `0..=end`"
57 _Self
="std::ops::RangeTo<Idx>",
58 label
="if you meant to iterate until a value, add a starting value",
59 note
="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
60 bounded `Range`: `0..end`"
63 _Self
="std::ops::RangeToInclusive<Idx>",
64 label
="if you meant to iterate until a value (including it), add a starting value",
65 note
="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
66 to have a bounded `RangeInclusive`: `0..=end`"
70 label
="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
73 _Self
="std::string::String",
74 label
="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
78 label
="borrow the array with `&` or call `.iter()` on it to iterate over it",
79 note
="arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
83 note
="if you want to iterate between `start` until a value `end`, use the exclusive range \
84 syntax `start..end` or the inclusive range syntax `start..=end`"
86 label
="`{Self}` is not an iterator",
87 message
="`{Self}` is not an iterator"
90 #[must_use = "iterators are lazy and do nothing unless consumed"]
92 /// The type of the elements being iterated over.
93 #[stable(feature = "rust1", since = "1.0.0")]
96 /// Advances the iterator and returns the next value.
98 /// Returns [`None`] when iteration is finished. Individual iterator
99 /// implementations may choose to resume iteration, and so calling `next()`
100 /// again may or may not eventually start returning [`Some(Item)`] again at some
103 /// [`None`]: ../../std/option/enum.Option.html#variant.None
104 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
111 /// let a = [1, 2, 3];
113 /// let mut iter = a.iter();
115 /// // A call to next() returns the next value...
116 /// assert_eq!(Some(&1), iter.next());
117 /// assert_eq!(Some(&2), iter.next());
118 /// assert_eq!(Some(&3), iter.next());
120 /// // ... and then None once it's over.
121 /// assert_eq!(None, iter.next());
123 /// // More calls may or may not return `None`. Here, they always will.
124 /// assert_eq!(None, iter.next());
125 /// assert_eq!(None, iter.next());
127 #[stable(feature = "rust1", since = "1.0.0")]
128 fn next(&mut self) -> Option
<Self::Item
>;
130 /// Returns the bounds on the remaining length of the iterator.
132 /// Specifically, `size_hint()` returns a tuple where the first element
133 /// is the lower bound, and the second element is the upper bound.
135 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
136 /// A [`None`] here means that either there is no known upper bound, or the
137 /// upper bound is larger than [`usize`].
139 /// # Implementation notes
141 /// It is not enforced that an iterator implementation yields the declared
142 /// number of elements. A buggy iterator may yield less than the lower bound
143 /// or more than the upper bound of elements.
145 /// `size_hint()` is primarily intended to be used for optimizations such as
146 /// reserving space for the elements of the iterator, but must not be
147 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
148 /// implementation of `size_hint()` should not lead to memory safety
151 /// That said, the implementation should provide a correct estimation,
152 /// because otherwise it would be a violation of the trait's protocol.
154 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
157 /// [`usize`]: ../../std/primitive.usize.html
158 /// [`Option`]: ../../std/option/enum.Option.html
159 /// [`None`]: ../../std/option/enum.Option.html#variant.None
166 /// let a = [1, 2, 3];
167 /// let iter = a.iter();
169 /// assert_eq!((3, Some(3)), iter.size_hint());
172 /// A more complex example:
175 /// // The even numbers from zero to ten.
176 /// let iter = (0..10).filter(|x| x % 2 == 0);
178 /// // We might iterate from zero to ten times. Knowing that it's five
179 /// // exactly wouldn't be possible without executing filter().
180 /// assert_eq!((0, Some(10)), iter.size_hint());
182 /// // Let's add five more numbers with chain()
183 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
185 /// // now both bounds are increased by five
186 /// assert_eq!((5, Some(15)), iter.size_hint());
189 /// Returning `None` for an upper bound:
192 /// // an infinite iterator has no upper bound
193 /// // and the maximum possible lower bound
196 /// assert_eq!((usize::max_value(), None), iter.size_hint());
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn size_hint(&self) -> (usize, Option
<usize>) { (0, None) }
202 /// Consumes the iterator, counting the number of iterations and returning it.
204 /// This method will call [`next`] repeatedly until [`None`] is encountered,
205 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
206 /// called at least once even if the iterator does not have any elements.
208 /// [`next`]: #tymethod.next
209 /// [`None`]: ../../std/option/enum.Option.html#variant.None
210 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
212 /// # Overflow Behavior
214 /// The method does no guarding against overflows, so counting elements of
215 /// an iterator with more than [`usize::MAX`] elements either produces the
216 /// wrong result or panics. If debug assertions are enabled, a panic is
221 /// This function might panic if the iterator has more than [`usize::MAX`]
224 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
231 /// let a = [1, 2, 3];
232 /// assert_eq!(a.iter().count(), 3);
234 /// let a = [1, 2, 3, 4, 5];
235 /// assert_eq!(a.iter().count(), 5);
238 #[stable(feature = "rust1", since = "1.0.0")]
239 fn count(self) -> usize where Self: Sized
{
241 fn add1
<T
>(count
: usize, _
: T
) -> usize {
249 /// Consumes the iterator, returning the last element.
251 /// This method will evaluate the iterator until it returns [`None`]. While
252 /// doing so, it keeps track of the current element. After [`None`] is
253 /// returned, `last()` will then return the last element it saw.
255 /// [`None`]: ../../std/option/enum.Option.html#variant.None
262 /// let a = [1, 2, 3];
263 /// assert_eq!(a.iter().last(), Some(&3));
265 /// let a = [1, 2, 3, 4, 5];
266 /// assert_eq!(a.iter().last(), Some(&5));
269 #[stable(feature = "rust1", since = "1.0.0")]
270 fn last(self) -> Option
<Self::Item
> where Self: Sized
{
272 fn some
<T
>(_
: Option
<T
>, x
: T
) -> Option
<T
> {
276 self.fold(None
, some
)
279 /// Returns the `n`th element of the iterator.
281 /// Like most indexing operations, the count starts from zero, so `nth(0)`
282 /// returns the first value, `nth(1)` the second, and so on.
284 /// Note that all preceding elements, as well as the returned element, will be
285 /// consumed from the iterator. That means that the preceding elements will be
286 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
287 /// will return different elements.
289 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
292 /// [`None`]: ../../std/option/enum.Option.html#variant.None
299 /// let a = [1, 2, 3];
300 /// assert_eq!(a.iter().nth(1), Some(&2));
303 /// Calling `nth()` multiple times doesn't rewind the iterator:
306 /// let a = [1, 2, 3];
308 /// let mut iter = a.iter();
310 /// assert_eq!(iter.nth(1), Some(&2));
311 /// assert_eq!(iter.nth(1), None);
314 /// Returning `None` if there are less than `n + 1` elements:
317 /// let a = [1, 2, 3];
318 /// assert_eq!(a.iter().nth(10), None);
321 #[stable(feature = "rust1", since = "1.0.0")]
322 fn nth(&mut self, mut n
: usize) -> Option
<Self::Item
> {
324 if n
== 0 { return Some(x) }
330 /// Creates an iterator starting at the same point, but stepping by
331 /// the given amount at each iteration.
333 /// Note 1: The first element of the iterator will always be returned,
334 /// regardless of the step given.
336 /// Note 2: The time at which ignored elements are pulled is not fixed.
337 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
338 /// but is also free to behave like the sequence
339 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
340 /// Which way is used may change for some iterators for performance reasons.
341 /// The second way will advance the iterator earlier and may consume more items.
343 /// `advance_n_and_return_first` is the equivalent of:
345 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
349 /// let next = iter.next();
350 /// if total_step > 1 {
351 /// iter.nth(total_step-2);
359 /// The method will panic if the given step is `0`.
366 /// let a = [0, 1, 2, 3, 4, 5];
367 /// let mut iter = a.iter().step_by(2);
369 /// assert_eq!(iter.next(), Some(&0));
370 /// assert_eq!(iter.next(), Some(&2));
371 /// assert_eq!(iter.next(), Some(&4));
372 /// assert_eq!(iter.next(), None);
375 #[stable(feature = "iterator_step_by", since = "1.28.0")]
376 fn step_by(self, step
: usize) -> StepBy
<Self> where Self: Sized
{
377 StepBy
::new(self, step
)
380 /// Takes two iterators and creates a new iterator over both in sequence.
382 /// `chain()` will return a new iterator which will first iterate over
383 /// values from the first iterator and then over values from the second
386 /// In other words, it links two iterators together, in a chain. 🔗
388 /// [`once`] is commonly used to adapt a single value into a chain of
389 /// other kinds of iteration.
396 /// let a1 = [1, 2, 3];
397 /// let a2 = [4, 5, 6];
399 /// let mut iter = a1.iter().chain(a2.iter());
401 /// assert_eq!(iter.next(), Some(&1));
402 /// assert_eq!(iter.next(), Some(&2));
403 /// assert_eq!(iter.next(), Some(&3));
404 /// assert_eq!(iter.next(), Some(&4));
405 /// assert_eq!(iter.next(), Some(&5));
406 /// assert_eq!(iter.next(), Some(&6));
407 /// assert_eq!(iter.next(), None);
410 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
411 /// anything that can be converted into an [`Iterator`], not just an
412 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
413 /// [`IntoIterator`], and so can be passed to `chain()` directly:
416 /// let s1 = &[1, 2, 3];
417 /// let s2 = &[4, 5, 6];
419 /// let mut iter = s1.iter().chain(s2);
421 /// assert_eq!(iter.next(), Some(&1));
422 /// assert_eq!(iter.next(), Some(&2));
423 /// assert_eq!(iter.next(), Some(&3));
424 /// assert_eq!(iter.next(), Some(&4));
425 /// assert_eq!(iter.next(), Some(&5));
426 /// assert_eq!(iter.next(), Some(&6));
427 /// assert_eq!(iter.next(), None);
430 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
434 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
435 /// use std::os::windows::ffi::OsStrExt;
436 /// s.encode_wide().chain(std::iter::once(0)).collect()
440 /// [`once`]: fn.once.html
441 /// [`Iterator`]: trait.Iterator.html
442 /// [`IntoIterator`]: trait.IntoIterator.html
443 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
445 #[stable(feature = "rust1", since = "1.0.0")]
446 fn chain
<U
>(self, other
: U
) -> Chain
<Self, U
::IntoIter
> where
447 Self: Sized
, U
: IntoIterator
<Item
=Self::Item
>,
449 Chain
::new(self, other
.into_iter())
452 /// 'Zips up' two iterators into a single iterator of pairs.
454 /// `zip()` returns a new iterator that will iterate over two other
455 /// iterators, returning a tuple where the first element comes from the
456 /// first iterator, and the second element comes from the second iterator.
458 /// In other words, it zips two iterators together, into a single one.
460 /// If either iterator returns [`None`], [`next`] from the zipped iterator
461 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
462 /// short-circuit and `next` will not be called on the second iterator.
469 /// let a1 = [1, 2, 3];
470 /// let a2 = [4, 5, 6];
472 /// let mut iter = a1.iter().zip(a2.iter());
474 /// assert_eq!(iter.next(), Some((&1, &4)));
475 /// assert_eq!(iter.next(), Some((&2, &5)));
476 /// assert_eq!(iter.next(), Some((&3, &6)));
477 /// assert_eq!(iter.next(), None);
480 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
481 /// anything that can be converted into an [`Iterator`], not just an
482 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
483 /// [`IntoIterator`], and so can be passed to `zip()` directly:
485 /// [`IntoIterator`]: trait.IntoIterator.html
486 /// [`Iterator`]: trait.Iterator.html
489 /// let s1 = &[1, 2, 3];
490 /// let s2 = &[4, 5, 6];
492 /// let mut iter = s1.iter().zip(s2);
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 /// `zip()` is often used to zip an infinite iterator to a finite one.
501 /// This works because the finite iterator will eventually return [`None`],
502 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
505 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
507 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
509 /// assert_eq!((0, 'f'), enumerate[0]);
510 /// assert_eq!((0, 'f'), zipper[0]);
512 /// assert_eq!((1, 'o'), enumerate[1]);
513 /// assert_eq!((1, 'o'), zipper[1]);
515 /// assert_eq!((2, 'o'), enumerate[2]);
516 /// assert_eq!((2, 'o'), zipper[2]);
519 /// [`enumerate`]: trait.Iterator.html#method.enumerate
520 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
521 /// [`None`]: ../../std/option/enum.Option.html#variant.None
523 #[stable(feature = "rust1", since = "1.0.0")]
524 fn zip
<U
>(self, other
: U
) -> Zip
<Self, U
::IntoIter
> where
525 Self: Sized
, U
: IntoIterator
527 Zip
::new(self, other
.into_iter())
530 /// Takes a closure and creates an iterator which calls that closure on each
533 /// `map()` transforms one iterator into another, by means of its argument:
534 /// something that implements [`FnMut`]. It produces a new iterator which
535 /// calls this closure on each element of the original iterator.
537 /// If you are good at thinking in types, you can think of `map()` like this:
538 /// If you have an iterator that gives you elements of some type `A`, and
539 /// you want an iterator of some other type `B`, you can use `map()`,
540 /// passing a closure that takes an `A` and returns a `B`.
542 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
543 /// lazy, it is best used when you're already working with other iterators.
544 /// If you're doing some sort of looping for a side effect, it's considered
545 /// more idiomatic to use [`for`] than `map()`.
547 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
548 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
555 /// let a = [1, 2, 3];
557 /// let mut iter = a.iter().map(|x| 2 * x);
559 /// assert_eq!(iter.next(), Some(2));
560 /// assert_eq!(iter.next(), Some(4));
561 /// assert_eq!(iter.next(), Some(6));
562 /// assert_eq!(iter.next(), None);
565 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
568 /// # #![allow(unused_must_use)]
569 /// // don't do this:
570 /// (0..5).map(|x| println!("{}", x));
572 /// // it won't even execute, as it is lazy. Rust will warn you about this.
574 /// // Instead, use for:
576 /// println!("{}", x);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 fn map
<B
, F
>(self, f
: F
) -> Map
<Self, F
> where
582 Self: Sized
, F
: FnMut(Self::Item
) -> B
,
587 /// Calls a closure on each element of an iterator.
589 /// This is equivalent to using a [`for`] loop on the iterator, although
590 /// `break` and `continue` are not possible from a closure. It's generally
591 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
592 /// when processing items at the end of longer iterator chains. In some
593 /// cases `for_each` may also be faster than a loop, because it will use
594 /// internal iteration on adaptors like `Chain`.
596 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
603 /// use std::sync::mpsc::channel;
605 /// let (tx, rx) = channel();
606 /// (0..5).map(|x| x * 2 + 1)
607 /// .for_each(move |x| tx.send(x).unwrap());
609 /// let v: Vec<_> = rx.iter().collect();
610 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
613 /// For such a small example, a `for` loop may be cleaner, but `for_each`
614 /// might be preferable to keep a functional style with longer iterators:
617 /// (0..5).flat_map(|x| x * 100 .. x * 110)
619 /// .filter(|&(i, x)| (i + x) % 3 == 0)
620 /// .for_each(|(i, x)| println!("{}:{}", i, x));
623 #[stable(feature = "iterator_for_each", since = "1.21.0")]
624 fn for_each
<F
>(self, f
: F
) where
625 Self: Sized
, F
: FnMut(Self::Item
),
628 fn call
<T
>(mut f
: impl FnMut(T
)) -> impl FnMut((), T
) {
629 move |(), item
| f(item
)
632 self.fold((), call(f
));
635 /// Creates an iterator which uses a closure to determine if an element
636 /// should be yielded.
638 /// The closure must return `true` or `false`. `filter()` creates an
639 /// iterator which calls this closure on each element. If the closure
640 /// returns `true`, then the element is returned. If the closure returns
641 /// `false`, it will try again, and call the closure on the next element,
642 /// seeing if it passes the test.
649 /// let a = [0i32, 1, 2];
651 /// let mut iter = a.iter().filter(|x| x.is_positive());
653 /// assert_eq!(iter.next(), Some(&1));
654 /// assert_eq!(iter.next(), Some(&2));
655 /// assert_eq!(iter.next(), None);
658 /// Because the closure passed to `filter()` takes a reference, and many
659 /// iterators iterate over references, this leads to a possibly confusing
660 /// situation, where the type of the closure is a double reference:
663 /// let a = [0, 1, 2];
665 /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
667 /// assert_eq!(iter.next(), Some(&2));
668 /// assert_eq!(iter.next(), None);
671 /// It's common to instead use destructuring on the argument to strip away
675 /// let a = [0, 1, 2];
677 /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
679 /// assert_eq!(iter.next(), Some(&2));
680 /// assert_eq!(iter.next(), None);
686 /// let a = [0, 1, 2];
688 /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
690 /// assert_eq!(iter.next(), Some(&2));
691 /// assert_eq!(iter.next(), None);
696 #[stable(feature = "rust1", since = "1.0.0")]
697 fn filter
<P
>(self, predicate
: P
) -> Filter
<Self, P
> where
698 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
700 Filter
::new(self, predicate
)
703 /// Creates an iterator that both filters and maps.
705 /// The closure must return an [`Option<T>`]. `filter_map` creates an
706 /// iterator which calls this closure on each element. If the closure
707 /// returns [`Some(element)`][`Some`], then that element is returned. If the
708 /// closure returns [`None`], it will try again, and call the closure on the
709 /// next element, seeing if it will return [`Some`].
711 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
714 /// [`filter`]: #method.filter
715 /// [`map`]: #method.map
717 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
719 /// In other words, it removes the [`Option<T>`] layer automatically. If your
720 /// mapping is already returning an [`Option<T>`] and you want to skip over
721 /// [`None`]s, then `filter_map` is much, much nicer to use.
728 /// let a = ["1", "lol", "3", "NaN", "5"];
730 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
732 /// assert_eq!(iter.next(), Some(1));
733 /// assert_eq!(iter.next(), Some(3));
734 /// assert_eq!(iter.next(), Some(5));
735 /// assert_eq!(iter.next(), None);
738 /// Here's the same example, but with [`filter`] and [`map`]:
741 /// let a = ["1", "lol", "3", "NaN", "5"];
742 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
743 /// assert_eq!(iter.next(), Some(1));
744 /// assert_eq!(iter.next(), Some(3));
745 /// assert_eq!(iter.next(), Some(5));
746 /// assert_eq!(iter.next(), None);
749 /// [`Option<T>`]: ../../std/option/enum.Option.html
750 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
751 /// [`None`]: ../../std/option/enum.Option.html#variant.None
753 #[stable(feature = "rust1", since = "1.0.0")]
754 fn filter_map
<B
, F
>(self, f
: F
) -> FilterMap
<Self, F
> where
755 Self: Sized
, F
: FnMut(Self::Item
) -> Option
<B
>,
757 FilterMap
::new(self, f
)
760 /// Creates an iterator which gives the current iteration count as well as
763 /// The iterator returned yields pairs `(i, val)`, where `i` is the
764 /// current index of iteration and `val` is the value returned by the
767 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
768 /// different sized integer, the [`zip`] function provides similar
771 /// # Overflow Behavior
773 /// The method does no guarding against overflows, so enumerating more than
774 /// [`usize::MAX`] elements either produces the wrong result or panics. If
775 /// debug assertions are enabled, a panic is guaranteed.
779 /// The returned iterator might panic if the to-be-returned index would
780 /// overflow a [`usize`].
782 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
783 /// [`usize`]: ../../std/primitive.usize.html
784 /// [`zip`]: #method.zip
789 /// let a = ['a', 'b', 'c'];
791 /// let mut iter = a.iter().enumerate();
793 /// assert_eq!(iter.next(), Some((0, &'a')));
794 /// assert_eq!(iter.next(), Some((1, &'b')));
795 /// assert_eq!(iter.next(), Some((2, &'c')));
796 /// assert_eq!(iter.next(), None);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 fn enumerate(self) -> Enumerate
<Self> where Self: Sized
{
804 /// Creates an iterator which can use `peek` to look at the next element of
805 /// the iterator without consuming it.
807 /// Adds a [`peek`] method to an iterator. See its documentation for
808 /// more information.
810 /// Note that the underlying iterator is still advanced when [`peek`] is
811 /// called for the first time: In order to retrieve the next element,
812 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
813 /// anything other than fetching the next value) of the [`next`] method
816 /// [`peek`]: struct.Peekable.html#method.peek
817 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
824 /// let xs = [1, 2, 3];
826 /// let mut iter = xs.iter().peekable();
828 /// // peek() lets us see into the future
829 /// assert_eq!(iter.peek(), Some(&&1));
830 /// assert_eq!(iter.next(), Some(&1));
832 /// assert_eq!(iter.next(), Some(&2));
834 /// // we can peek() multiple times, the iterator won't advance
835 /// assert_eq!(iter.peek(), Some(&&3));
836 /// assert_eq!(iter.peek(), Some(&&3));
838 /// assert_eq!(iter.next(), Some(&3));
840 /// // after the iterator is finished, so is peek()
841 /// assert_eq!(iter.peek(), None);
842 /// assert_eq!(iter.next(), None);
845 #[stable(feature = "rust1", since = "1.0.0")]
846 fn peekable(self) -> Peekable
<Self> where Self: Sized
{
850 /// Creates an iterator that [`skip`]s elements based on a predicate.
852 /// [`skip`]: #method.skip
854 /// `skip_while()` takes a closure as an argument. It will call this
855 /// closure on each element of the iterator, and ignore elements
856 /// until it returns `false`.
858 /// After `false` is returned, `skip_while()`'s job is over, and the
859 /// rest of the elements are yielded.
866 /// let a = [-1i32, 0, 1];
868 /// let mut iter = a.iter().skip_while(|x| x.is_negative());
870 /// assert_eq!(iter.next(), Some(&0));
871 /// assert_eq!(iter.next(), Some(&1));
872 /// assert_eq!(iter.next(), None);
875 /// Because the closure passed to `skip_while()` takes a reference, and many
876 /// iterators iterate over references, this leads to a possibly confusing
877 /// situation, where the type of the closure is a double reference:
880 /// let a = [-1, 0, 1];
882 /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
884 /// assert_eq!(iter.next(), Some(&0));
885 /// assert_eq!(iter.next(), Some(&1));
886 /// assert_eq!(iter.next(), None);
889 /// Stopping after an initial `false`:
892 /// let a = [-1, 0, 1, -2];
894 /// let mut iter = a.iter().skip_while(|x| **x < 0);
896 /// assert_eq!(iter.next(), Some(&0));
897 /// assert_eq!(iter.next(), Some(&1));
899 /// // while this would have been false, since we already got a false,
900 /// // skip_while() isn't used any more
901 /// assert_eq!(iter.next(), Some(&-2));
903 /// assert_eq!(iter.next(), None);
906 #[stable(feature = "rust1", since = "1.0.0")]
907 fn skip_while
<P
>(self, predicate
: P
) -> SkipWhile
<Self, P
> where
908 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
910 SkipWhile
::new(self, predicate
)
913 /// Creates an iterator that yields elements based on a predicate.
915 /// `take_while()` takes a closure as an argument. It will call this
916 /// closure on each element of the iterator, and yield elements
917 /// while it returns `true`.
919 /// After `false` is returned, `take_while()`'s job is over, and the
920 /// rest of the elements are ignored.
927 /// let a = [-1i32, 0, 1];
929 /// let mut iter = a.iter().take_while(|x| x.is_negative());
931 /// assert_eq!(iter.next(), Some(&-1));
932 /// assert_eq!(iter.next(), None);
935 /// Because the closure passed to `take_while()` takes a reference, and many
936 /// iterators iterate over references, this leads to a possibly confusing
937 /// situation, where the type of the closure is a double reference:
940 /// let a = [-1, 0, 1];
942 /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
944 /// assert_eq!(iter.next(), Some(&-1));
945 /// assert_eq!(iter.next(), None);
948 /// Stopping after an initial `false`:
951 /// let a = [-1, 0, 1, -2];
953 /// let mut iter = a.iter().take_while(|x| **x < 0);
955 /// assert_eq!(iter.next(), Some(&-1));
957 /// // We have more elements that are less than zero, but since we already
958 /// // got a false, take_while() isn't used any more
959 /// assert_eq!(iter.next(), None);
962 /// Because `take_while()` needs to look at the value in order to see if it
963 /// should be included or not, consuming iterators will see that it is
967 /// let a = [1, 2, 3, 4];
968 /// let mut iter = a.iter();
970 /// let result: Vec<i32> = iter.by_ref()
971 /// .take_while(|n| **n != 3)
975 /// assert_eq!(result, &[1, 2]);
977 /// let result: Vec<i32> = iter.cloned().collect();
979 /// assert_eq!(result, &[4]);
982 /// The `3` is no longer there, because it was consumed in order to see if
983 /// the iteration should stop, but wasn't placed back into the iterator.
985 #[stable(feature = "rust1", since = "1.0.0")]
986 fn take_while
<P
>(self, predicate
: P
) -> TakeWhile
<Self, P
> where
987 Self: Sized
, P
: FnMut(&Self::Item
) -> bool
,
989 TakeWhile
::new(self, predicate
)
992 /// Creates an iterator that skips the first `n` elements.
994 /// After they have been consumed, the rest of the elements are yielded.
995 /// Rather than overriding this method directly, instead override the `nth` method.
1002 /// let a = [1, 2, 3];
1004 /// let mut iter = a.iter().skip(2);
1006 /// assert_eq!(iter.next(), Some(&3));
1007 /// assert_eq!(iter.next(), None);
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 fn skip(self, n
: usize) -> Skip
<Self> where Self: Sized
{
1015 /// Creates an iterator that yields its first `n` elements.
1022 /// let a = [1, 2, 3];
1024 /// let mut iter = a.iter().take(2);
1026 /// assert_eq!(iter.next(), Some(&1));
1027 /// assert_eq!(iter.next(), Some(&2));
1028 /// assert_eq!(iter.next(), None);
1031 /// `take()` is often used with an infinite iterator, to make it finite:
1034 /// let mut iter = (0..).take(3);
1036 /// assert_eq!(iter.next(), Some(0));
1037 /// assert_eq!(iter.next(), Some(1));
1038 /// assert_eq!(iter.next(), Some(2));
1039 /// assert_eq!(iter.next(), None);
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 fn take(self, n
: usize) -> Take
<Self> where Self: Sized
, {
1047 /// An iterator adaptor similar to [`fold`] that holds internal state and
1048 /// produces a new iterator.
1050 /// [`fold`]: #method.fold
1052 /// `scan()` takes two arguments: an initial value which seeds the internal
1053 /// state, and a closure with two arguments, the first being a mutable
1054 /// reference to the internal state and the second an iterator element.
1055 /// The closure can assign to the internal state to share state between
1058 /// On iteration, the closure will be applied to each element of the
1059 /// iterator and the return value from the closure, an [`Option`], is
1060 /// yielded by the iterator.
1062 /// [`Option`]: ../../std/option/enum.Option.html
1069 /// let a = [1, 2, 3];
1071 /// let mut iter = a.iter().scan(1, |state, &x| {
1072 /// // each iteration, we'll multiply the state by the element
1073 /// *state = *state * x;
1075 /// // then, we'll yield the negation of the state
1079 /// assert_eq!(iter.next(), Some(-1));
1080 /// assert_eq!(iter.next(), Some(-2));
1081 /// assert_eq!(iter.next(), Some(-6));
1082 /// assert_eq!(iter.next(), None);
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 fn scan
<St
, B
, F
>(self, initial_state
: St
, f
: F
) -> Scan
<Self, St
, F
>
1087 where Self: Sized
, F
: FnMut(&mut St
, Self::Item
) -> Option
<B
>,
1089 Scan
::new(self, initial_state
, f
)
1092 /// Creates an iterator that works like map, but flattens nested structure.
1094 /// The [`map`] adapter is very useful, but only when the closure
1095 /// argument produces values. If it produces an iterator instead, there's
1096 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1099 /// You can think of `flat_map(f)` as the semantic equivalent
1100 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1102 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1103 /// one item for each element, and `flat_map()`'s closure returns an
1104 /// iterator for each element.
1106 /// [`map`]: #method.map
1107 /// [`flatten`]: #method.flatten
1114 /// let words = ["alpha", "beta", "gamma"];
1116 /// // chars() returns an iterator
1117 /// let merged: String = words.iter()
1118 /// .flat_map(|s| s.chars())
1120 /// assert_eq!(merged, "alphabetagamma");
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 fn flat_map
<U
, F
>(self, f
: F
) -> FlatMap
<Self, U
, F
>
1125 where Self: Sized
, U
: IntoIterator
, F
: FnMut(Self::Item
) -> U
,
1127 FlatMap
::new(self, f
)
1130 /// Creates an iterator that flattens nested structure.
1132 /// This is useful when you have an iterator of iterators or an iterator of
1133 /// things that can be turned into iterators and you want to remove one
1134 /// level of indirection.
1141 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1142 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1143 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1146 /// Mapping and then flattening:
1149 /// let words = ["alpha", "beta", "gamma"];
1151 /// // chars() returns an iterator
1152 /// let merged: String = words.iter()
1153 /// .map(|s| s.chars())
1156 /// assert_eq!(merged, "alphabetagamma");
1159 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1160 /// in this case since it conveys intent more clearly:
1163 /// let words = ["alpha", "beta", "gamma"];
1165 /// // chars() returns an iterator
1166 /// let merged: String = words.iter()
1167 /// .flat_map(|s| s.chars())
1169 /// assert_eq!(merged, "alphabetagamma");
1172 /// Flattening once only removes one level of nesting:
1175 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1177 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1178 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1180 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1181 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1184 /// Here we see that `flatten()` does not perform a "deep" flatten.
1185 /// Instead, only one level of nesting is removed. That is, if you
1186 /// `flatten()` a three-dimensional array the result will be
1187 /// two-dimensional and not one-dimensional. To get a one-dimensional
1188 /// structure, you have to `flatten()` again.
1190 /// [`flat_map()`]: #method.flat_map
1192 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1193 fn flatten(self) -> Flatten
<Self>
1194 where Self: Sized
, Self::Item
: IntoIterator
{
1198 /// Creates an iterator which ends after the first [`None`].
1200 /// After an iterator returns [`None`], future calls may or may not yield
1201 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1202 /// [`None`] is given, it will always return [`None`] forever.
1204 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1205 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1212 /// // an iterator which alternates between Some and None
1213 /// struct Alternate {
1217 /// impl Iterator for Alternate {
1218 /// type Item = i32;
1220 /// fn next(&mut self) -> Option<i32> {
1221 /// let val = self.state;
1222 /// self.state = self.state + 1;
1224 /// // if it's even, Some(i32), else None
1225 /// if val % 2 == 0 {
1233 /// let mut iter = Alternate { state: 0 };
1235 /// // we can see our iterator going back and forth
1236 /// assert_eq!(iter.next(), Some(0));
1237 /// assert_eq!(iter.next(), None);
1238 /// assert_eq!(iter.next(), Some(2));
1239 /// assert_eq!(iter.next(), None);
1241 /// // however, once we fuse it...
1242 /// let mut iter = iter.fuse();
1244 /// assert_eq!(iter.next(), Some(4));
1245 /// assert_eq!(iter.next(), None);
1247 /// // it will always return `None` after the first time.
1248 /// assert_eq!(iter.next(), None);
1249 /// assert_eq!(iter.next(), None);
1250 /// assert_eq!(iter.next(), None);
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 fn fuse(self) -> Fuse
<Self> where Self: Sized
{
1258 /// Does something with each element of an iterator, passing the value on.
1260 /// When using iterators, you'll often chain several of them together.
1261 /// While working on such code, you might want to check out what's
1262 /// happening at various parts in the pipeline. To do that, insert
1263 /// a call to `inspect()`.
1265 /// It's more common for `inspect()` to be used as a debugging tool than to
1266 /// exist in your final code, but applications may find it useful in certain
1267 /// situations when errors need to be logged before being discarded.
1274 /// let a = [1, 4, 2, 3];
1276 /// // this iterator sequence is complex.
1277 /// let sum = a.iter()
1279 /// .filter(|x| x % 2 == 0)
1280 /// .fold(0, |sum, i| sum + i);
1282 /// println!("{}", sum);
1284 /// // let's add some inspect() calls to investigate what's happening
1285 /// let sum = a.iter()
1287 /// .inspect(|x| println!("about to filter: {}", x))
1288 /// .filter(|x| x % 2 == 0)
1289 /// .inspect(|x| println!("made it through filter: {}", x))
1290 /// .fold(0, |sum, i| sum + i);
1292 /// println!("{}", sum);
1295 /// This will print:
1299 /// about to filter: 1
1300 /// about to filter: 4
1301 /// made it through filter: 4
1302 /// about to filter: 2
1303 /// made it through filter: 2
1304 /// about to filter: 3
1308 /// Logging errors before discarding them:
1311 /// let lines = ["1", "2", "a"];
1313 /// let sum: i32 = lines
1315 /// .map(|line| line.parse::<i32>())
1316 /// .inspect(|num| {
1317 /// if let Err(ref e) = *num {
1318 /// println!("Parsing error: {}", e);
1321 /// .filter_map(Result::ok)
1324 /// println!("Sum: {}", sum);
1327 /// This will print:
1330 /// Parsing error: invalid digit found in string
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 fn inspect
<F
>(self, f
: F
) -> Inspect
<Self, F
> where
1336 Self: Sized
, F
: FnMut(&Self::Item
),
1338 Inspect
::new(self, f
)
1341 /// Borrows an iterator, rather than consuming it.
1343 /// This is useful to allow applying iterator adaptors while still
1344 /// retaining ownership of the original iterator.
1351 /// let a = [1, 2, 3];
1353 /// let iter = a.iter();
1355 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1357 /// assert_eq!(sum, 6);
1359 /// // if we try to use iter again, it won't work. The following line
1360 /// // gives "error: use of moved value: `iter`
1361 /// // assert_eq!(iter.next(), None);
1363 /// // let's try that again
1364 /// let a = [1, 2, 3];
1366 /// let mut iter = a.iter();
1368 /// // instead, we add in a .by_ref()
1369 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1371 /// assert_eq!(sum, 3);
1373 /// // now this is just fine:
1374 /// assert_eq!(iter.next(), Some(&3));
1375 /// assert_eq!(iter.next(), None);
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1380 /// Transforms an iterator into a collection.
1382 /// `collect()` can take anything iterable, and turn it into a relevant
1383 /// collection. This is one of the more powerful methods in the standard
1384 /// library, used in a variety of contexts.
1386 /// The most basic pattern in which `collect()` is used is to turn one
1387 /// collection into another. You take a collection, call [`iter`] on it,
1388 /// do a bunch of transformations, and then `collect()` at the end.
1390 /// One of the keys to `collect()`'s power is that many things you might
1391 /// not think of as 'collections' actually are. For example, a [`String`]
1392 /// is a collection of [`char`]s. And a collection of
1393 /// [`Result<T, E>`][`Result`] can be thought of as single
1394 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1396 /// Because `collect()` is so general, it can cause problems with type
1397 /// inference. As such, `collect()` is one of the few times you'll see
1398 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1399 /// helps the inference algorithm understand specifically which collection
1400 /// you're trying to collect into.
1407 /// let a = [1, 2, 3];
1409 /// let doubled: Vec<i32> = a.iter()
1410 /// .map(|&x| x * 2)
1413 /// assert_eq!(vec![2, 4, 6], doubled);
1416 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1417 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1419 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1422 /// use std::collections::VecDeque;
1424 /// let a = [1, 2, 3];
1426 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1428 /// assert_eq!(2, doubled[0]);
1429 /// assert_eq!(4, doubled[1]);
1430 /// assert_eq!(6, doubled[2]);
1433 /// Using the 'turbofish' instead of annotating `doubled`:
1436 /// let a = [1, 2, 3];
1438 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1440 /// assert_eq!(vec![2, 4, 6], doubled);
1443 /// Because `collect()` only cares about what you're collecting into, you can
1444 /// still use a partial type hint, `_`, with the turbofish:
1447 /// let a = [1, 2, 3];
1449 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1451 /// assert_eq!(vec![2, 4, 6], doubled);
1454 /// Using `collect()` to make a [`String`]:
1457 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1459 /// let hello: String = chars.iter()
1460 /// .map(|&x| x as u8)
1461 /// .map(|x| (x + 1) as char)
1464 /// assert_eq!("hello", hello);
1467 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1468 /// see if any of them failed:
1471 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1473 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1475 /// // gives us the first error
1476 /// assert_eq!(Err("nope"), result);
1478 /// let results = [Ok(1), Ok(3)];
1480 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1482 /// // gives us the list of answers
1483 /// assert_eq!(Ok(vec![1, 3]), result);
1486 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1487 /// [`String`]: ../../std/string/struct.String.html
1488 /// [`char`]: ../../std/primitive.char.html
1489 /// [`Result`]: ../../std/result/enum.Result.html
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1493 fn collect
<B
: FromIterator
<Self::Item
>>(self) -> B
where Self: Sized
{
1494 FromIterator
::from_iter(self)
1497 /// Consumes an iterator, creating two collections from it.
1499 /// The predicate passed to `partition()` can return `true`, or `false`.
1500 /// `partition()` returns a pair, all of the elements for which it returned
1501 /// `true`, and all of the elements for which it returned `false`.
1503 /// See also [`is_partitioned()`] and [`partition_in_place()`].
1505 /// [`is_partitioned()`]: #method.is_partitioned
1506 /// [`partition_in_place()`]: #method.partition_in_place
1513 /// let a = [1, 2, 3];
1515 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1517 /// .partition(|&n| n % 2 == 0);
1519 /// assert_eq!(even, vec![2]);
1520 /// assert_eq!(odd, vec![1, 3]);
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 fn partition
<B
, F
>(self, f
: F
) -> (B
, B
) where
1525 B
: Default
+ Extend
<Self::Item
>,
1526 F
: FnMut(&Self::Item
) -> bool
1529 fn extend
<'a
, T
, B
: Extend
<T
>>(
1530 mut f
: impl FnMut(&T
) -> bool
+ 'a
,
1533 ) -> impl FnMut(T
) + 'a
{
1536 left
.extend(Some(x
));
1538 right
.extend(Some(x
));
1543 let mut left
: B
= Default
::default();
1544 let mut right
: B
= Default
::default();
1546 self.for_each(extend(f
, &mut left
, &mut right
));
1551 /// Reorders the elements of this iterator *in-place* according to the given predicate,
1552 /// such that all those that return `true` precede all those that return `false`.
1553 /// Returns the number of `true` elements found.
1555 /// The relative order of partitioned items is not maintained.
1557 /// See also [`is_partitioned()`] and [`partition()`].
1559 /// [`is_partitioned()`]: #method.is_partitioned
1560 /// [`partition()`]: #method.partition
1565 /// #![feature(iter_partition_in_place)]
1567 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1569 /// // Partition in-place between evens and odds
1570 /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1572 /// assert_eq!(i, 3);
1573 /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1574 /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1576 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1577 fn partition_in_place
<'a
, T
: 'a
, P
>(mut self, ref mut predicate
: P
) -> usize
1579 Self: Sized
+ DoubleEndedIterator
<Item
= &'a
mut T
>,
1580 P
: FnMut(&T
) -> bool
,
1582 // FIXME: should we worry about the count overflowing? The only way to have more than
1583 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1585 // These closure "factory" functions exist to avoid genericity in `Self`.
1589 predicate
: &'a
mut impl FnMut(&T
) -> bool
,
1590 true_count
: &'a
mut usize,
1591 ) -> impl FnMut(&&mut T
) -> bool
+ 'a
{
1593 let p
= predicate(&**x
);
1594 *true_count
+= p
as usize;
1601 predicate
: &mut impl FnMut(&T
) -> bool
1602 ) -> impl FnMut(&&mut T
) -> bool
+ '_
{
1603 move |x
| predicate(&**x
)
1606 // Repeatedly find the first `false` and swap it with the last `true`.
1607 let mut true_count
= 0;
1608 while let Some(head
) = self.find(is_false(predicate
, &mut true_count
)) {
1609 if let Some(tail
) = self.rfind(is_true(predicate
)) {
1610 crate::mem
::swap(head
, tail
);
1619 /// Checks if the elements of this iterator are partitioned according to the given predicate,
1620 /// such that all those that return `true` precede all those that return `false`.
1622 /// See also [`partition()`] and [`partition_in_place()`].
1624 /// [`partition()`]: #method.partition
1625 /// [`partition_in_place()`]: #method.partition_in_place
1630 /// #![feature(iter_is_partitioned)]
1632 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1633 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1635 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1636 fn is_partitioned
<P
>(mut self, mut predicate
: P
) -> bool
1639 P
: FnMut(Self::Item
) -> bool
,
1641 // Either all items test `true`, or the first clause stops at `false`
1642 // and we check that there are no more `true` items after that.
1643 self.all(&mut predicate
) || !self.any(predicate
)
1646 /// An iterator method that applies a function as long as it returns
1647 /// successfully, producing a single, final value.
1649 /// `try_fold()` takes two arguments: an initial value, and a closure with
1650 /// two arguments: an 'accumulator', and an element. The closure either
1651 /// returns successfully, with the value that the accumulator should have
1652 /// for the next iteration, or it returns failure, with an error value that
1653 /// is propagated back to the caller immediately (short-circuiting).
1655 /// The initial value is the value the accumulator will have on the first
1656 /// call. If applying the closure succeeded against every element of the
1657 /// iterator, `try_fold()` returns the final accumulator as success.
1659 /// Folding is useful whenever you have a collection of something, and want
1660 /// to produce a single value from it.
1662 /// # Note to Implementors
1664 /// Most of the other (forward) methods have default implementations in
1665 /// terms of this one, so try to implement this explicitly if it can
1666 /// do something better than the default `for` loop implementation.
1668 /// In particular, try to have this call `try_fold()` on the internal parts
1669 /// from which this iterator is composed. If multiple calls are needed,
1670 /// the `?` operator may be convenient for chaining the accumulator value
1671 /// along, but beware any invariants that need to be upheld before those
1672 /// early returns. This is a `&mut self` method, so iteration needs to be
1673 /// resumable after hitting an error here.
1680 /// let a = [1, 2, 3];
1682 /// // the checked sum of all of the elements of the array
1683 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1685 /// assert_eq!(sum, Some(6));
1688 /// Short-circuiting:
1691 /// let a = [10, 20, 30, 100, 40, 50];
1692 /// let mut it = a.iter();
1694 /// // This sum overflows when adding the 100 element
1695 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1696 /// assert_eq!(sum, None);
1698 /// // Because it short-circuited, the remaining elements are still
1699 /// // available through the iterator.
1700 /// assert_eq!(it.len(), 2);
1701 /// assert_eq!(it.next(), Some(&40));
1704 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1705 fn try_fold
<B
, F
, R
>(&mut self, init
: B
, mut f
: F
) -> R
where
1706 Self: Sized
, F
: FnMut(B
, Self::Item
) -> R
, R
: Try
<Ok
=B
>
1708 let mut accum
= init
;
1709 while let Some(x
) = self.next() {
1710 accum
= f(accum
, x
)?
;
1715 /// An iterator method that applies a fallible function to each item in the
1716 /// iterator, stopping at the first error and returning that error.
1718 /// This can also be thought of as the fallible form of [`for_each()`]
1719 /// or as the stateless version of [`try_fold()`].
1721 /// [`for_each()`]: #method.for_each
1722 /// [`try_fold()`]: #method.try_fold
1727 /// use std::fs::rename;
1728 /// use std::io::{stdout, Write};
1729 /// use std::path::Path;
1731 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1733 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1734 /// assert!(res.is_ok());
1736 /// let mut it = data.iter().cloned();
1737 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1738 /// assert!(res.is_err());
1739 /// // It short-circuited, so the remaining items are still in the iterator:
1740 /// assert_eq!(it.next(), Some("stale_bread.json"));
1743 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1744 fn try_for_each
<F
, R
>(&mut self, f
: F
) -> R
where
1745 Self: Sized
, F
: FnMut(Self::Item
) -> R
, R
: Try
<Ok
=()>
1748 fn call
<T
, R
>(mut f
: impl FnMut(T
) -> R
) -> impl FnMut((), T
) -> R
{
1752 self.try_fold((), call(f
))
1755 /// An iterator method that applies a function, producing a single, final value.
1757 /// `fold()` takes two arguments: an initial value, and a closure with two
1758 /// arguments: an 'accumulator', and an element. The closure returns the value that
1759 /// the accumulator should have for the next iteration.
1761 /// The initial value is the value the accumulator will have on the first
1764 /// After applying this closure to every element of the iterator, `fold()`
1765 /// returns the accumulator.
1767 /// This operation is sometimes called 'reduce' or 'inject'.
1769 /// Folding is useful whenever you have a collection of something, and want
1770 /// to produce a single value from it.
1772 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1773 /// may not terminate for infinite iterators, even on traits for which a
1774 /// result is determinable in finite time.
1781 /// let a = [1, 2, 3];
1783 /// // the sum of all of the elements of the array
1784 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1786 /// assert_eq!(sum, 6);
1789 /// Let's walk through each step of the iteration here:
1791 /// | element | acc | x | result |
1792 /// |---------|-----|---|--------|
1794 /// | 1 | 0 | 1 | 1 |
1795 /// | 2 | 1 | 2 | 3 |
1796 /// | 3 | 3 | 3 | 6 |
1798 /// And so, our final result, `6`.
1800 /// It's common for people who haven't used iterators a lot to
1801 /// use a `for` loop with a list of things to build up a result. Those
1802 /// can be turned into `fold()`s:
1804 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1807 /// let numbers = [1, 2, 3, 4, 5];
1809 /// let mut result = 0;
1812 /// for i in &numbers {
1813 /// result = result + i;
1817 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1819 /// // they're the same
1820 /// assert_eq!(result, result2);
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 fn fold
<B
, F
>(mut self, init
: B
, f
: F
) -> B
where
1825 Self: Sized
, F
: FnMut(B
, Self::Item
) -> B
,
1828 fn ok
<B
, T
>(mut f
: impl FnMut(B
, T
) -> B
) -> impl FnMut(B
, T
) -> Result
<B
, !> {
1829 move |acc
, x
| Ok(f(acc
, x
))
1832 self.try_fold(init
, ok(f
)).unwrap()
1835 /// Tests if every element of the iterator matches a predicate.
1837 /// `all()` takes a closure that returns `true` or `false`. It applies
1838 /// this closure to each element of the iterator, and if they all return
1839 /// `true`, then so does `all()`. If any of them return `false`, it
1840 /// returns `false`.
1842 /// `all()` is short-circuiting; in other words, it will stop processing
1843 /// as soon as it finds a `false`, given that no matter what else happens,
1844 /// the result will also be `false`.
1846 /// An empty iterator returns `true`.
1853 /// let a = [1, 2, 3];
1855 /// assert!(a.iter().all(|&x| x > 0));
1857 /// assert!(!a.iter().all(|&x| x > 2));
1860 /// Stopping at the first `false`:
1863 /// let a = [1, 2, 3];
1865 /// let mut iter = a.iter();
1867 /// assert!(!iter.all(|&x| x != 2));
1869 /// // we can still use `iter`, as there are more elements.
1870 /// assert_eq!(iter.next(), Some(&3));
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 fn all
<F
>(&mut self, f
: F
) -> bool
where
1875 Self: Sized
, F
: FnMut(Self::Item
) -> bool
1878 fn check
<T
>(mut f
: impl FnMut(T
) -> bool
) -> impl FnMut((), T
) -> LoopState
<(), ()> {
1880 if f(x
) { LoopState::Continue(()) }
1881 else { LoopState::Break(()) }
1884 self.try_fold((), check(f
)) == LoopState
::Continue(())
1887 /// Tests if any element of the iterator matches a predicate.
1889 /// `any()` takes a closure that returns `true` or `false`. It applies
1890 /// this closure to each element of the iterator, and if any of them return
1891 /// `true`, then so does `any()`. If they all return `false`, it
1892 /// returns `false`.
1894 /// `any()` is short-circuiting; in other words, it will stop processing
1895 /// as soon as it finds a `true`, given that no matter what else happens,
1896 /// the result will also be `true`.
1898 /// An empty iterator returns `false`.
1905 /// let a = [1, 2, 3];
1907 /// assert!(a.iter().any(|&x| x > 0));
1909 /// assert!(!a.iter().any(|&x| x > 5));
1912 /// Stopping at the first `true`:
1915 /// let a = [1, 2, 3];
1917 /// let mut iter = a.iter();
1919 /// assert!(iter.any(|&x| x != 2));
1921 /// // we can still use `iter`, as there are more elements.
1922 /// assert_eq!(iter.next(), Some(&2));
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 fn any
<F
>(&mut self, f
: F
) -> bool
where
1928 F
: FnMut(Self::Item
) -> bool
1931 fn check
<T
>(mut f
: impl FnMut(T
) -> bool
) -> impl FnMut((), T
) -> LoopState
<(), ()> {
1933 if f(x
) { LoopState::Break(()) }
1934 else { LoopState::Continue(()) }
1938 self.try_fold((), check(f
)) == LoopState
::Break(())
1941 /// Searches for an element of an iterator that satisfies a predicate.
1943 /// `find()` takes a closure that returns `true` or `false`. It applies
1944 /// this closure to each element of the iterator, and if any of them return
1945 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1946 /// `false`, it returns [`None`].
1948 /// `find()` is short-circuiting; in other words, it will stop processing
1949 /// as soon as the closure returns `true`.
1951 /// Because `find()` takes a reference, and many iterators iterate over
1952 /// references, this leads to a possibly confusing situation where the
1953 /// argument is a double reference. You can see this effect in the
1954 /// examples below, with `&&x`.
1956 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1957 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1964 /// let a = [1, 2, 3];
1966 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1968 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1971 /// Stopping at the first `true`:
1974 /// let a = [1, 2, 3];
1976 /// let mut iter = a.iter();
1978 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1980 /// // we can still use `iter`, as there are more elements.
1981 /// assert_eq!(iter.next(), Some(&3));
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 fn find
<P
>(&mut self, predicate
: P
) -> Option
<Self::Item
> where
1987 P
: FnMut(&Self::Item
) -> bool
,
1991 mut predicate
: impl FnMut(&T
) -> bool
1992 ) -> impl FnMut((), T
) -> LoopState
<(), T
> {
1994 if predicate(&x
) { LoopState::Break(x) }
1995 else { LoopState::Continue(()) }
1999 self.try_fold((), check(predicate
)).break_value()
2002 /// Applies function to the elements of iterator and returns
2003 /// the first non-none result.
2005 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2011 /// let a = ["lol", "NaN", "2", "5"];
2013 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2015 /// assert_eq!(first_number, Some(2));
2018 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2019 fn find_map
<B
, F
>(&mut self, f
: F
) -> Option
<B
> where
2021 F
: FnMut(Self::Item
) -> Option
<B
>,
2024 fn check
<T
, B
>(mut f
: impl FnMut(T
) -> Option
<B
>) -> impl FnMut((), T
) -> LoopState
<(), B
> {
2025 move |(), x
| match f(x
) {
2026 Some(x
) => LoopState
::Break(x
),
2027 None
=> LoopState
::Continue(()),
2031 self.try_fold((), check(f
)).break_value()
2034 /// Searches for an element in an iterator, returning its index.
2036 /// `position()` takes a closure that returns `true` or `false`. It applies
2037 /// this closure to each element of the iterator, and if one of them
2038 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2039 /// them return `false`, it returns [`None`].
2041 /// `position()` is short-circuiting; in other words, it will stop
2042 /// processing as soon as it finds a `true`.
2044 /// # Overflow Behavior
2046 /// The method does no guarding against overflows, so if there are more
2047 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2048 /// result or panics. If debug assertions are enabled, a panic is
2053 /// This function might panic if the iterator has more than `usize::MAX`
2054 /// non-matching elements.
2056 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2057 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2058 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
2065 /// let a = [1, 2, 3];
2067 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2069 /// assert_eq!(a.iter().position(|&x| x == 5), None);
2072 /// Stopping at the first `true`:
2075 /// let a = [1, 2, 3, 4];
2077 /// let mut iter = a.iter();
2079 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2081 /// // we can still use `iter`, as there are more elements.
2082 /// assert_eq!(iter.next(), Some(&3));
2084 /// // The returned index depends on iterator state
2085 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 fn position
<P
>(&mut self, predicate
: P
) -> Option
<usize> where
2092 P
: FnMut(Self::Item
) -> bool
,
2096 mut predicate
: impl FnMut(T
) -> bool
,
2097 ) -> impl FnMut(usize, T
) -> LoopState
<usize, usize> {
2098 // The addition might panic on overflow
2100 if predicate(x
) { LoopState::Break(i) }
2101 else { LoopState::Continue(Add::add(i, 1)) }
2105 self.try_fold(0, check(predicate
)).break_value()
2108 /// Searches for an element in an iterator from the right, returning its
2111 /// `rposition()` takes a closure that returns `true` or `false`. It applies
2112 /// this closure to each element of the iterator, starting from the end,
2113 /// and if one of them returns `true`, then `rposition()` returns
2114 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2116 /// `rposition()` is short-circuiting; in other words, it will stop
2117 /// processing as soon as it finds a `true`.
2119 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2120 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2127 /// let a = [1, 2, 3];
2129 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2131 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2134 /// Stopping at the first `true`:
2137 /// let a = [1, 2, 3];
2139 /// let mut iter = a.iter();
2141 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2143 /// // we can still use `iter`, as there are more elements.
2144 /// assert_eq!(iter.next(), Some(&1));
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 fn rposition
<P
>(&mut self, predicate
: P
) -> Option
<usize> where
2149 P
: FnMut(Self::Item
) -> bool
,
2150 Self: Sized
+ ExactSizeIterator
+ DoubleEndedIterator
2152 // No need for an overflow check here, because `ExactSizeIterator`
2153 // implies that the number of elements fits into a `usize`.
2156 mut predicate
: impl FnMut(T
) -> bool
,
2157 ) -> impl FnMut(usize, T
) -> LoopState
<usize, usize> {
2160 if predicate(x
) { LoopState::Break(i) }
2161 else { LoopState::Continue(i) }
2166 self.try_rfold(n
, check(predicate
)).break_value()
2169 /// Returns the maximum element of an iterator.
2171 /// If several elements are equally maximum, the last element is
2172 /// returned. If the iterator is empty, [`None`] is returned.
2174 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2181 /// let a = [1, 2, 3];
2182 /// let b: Vec<u32> = Vec::new();
2184 /// assert_eq!(a.iter().max(), Some(&3));
2185 /// assert_eq!(b.iter().max(), None);
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 fn max(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
2191 self.max_by(Ord
::cmp
)
2194 /// Returns the minimum element of an iterator.
2196 /// If several elements are equally minimum, the first element is
2197 /// returned. If the iterator is empty, [`None`] is returned.
2199 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2206 /// let a = [1, 2, 3];
2207 /// let b: Vec<u32> = Vec::new();
2209 /// assert_eq!(a.iter().min(), Some(&1));
2210 /// assert_eq!(b.iter().min(), None);
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 fn min(self) -> Option
<Self::Item
> where Self: Sized
, Self::Item
: Ord
2216 self.min_by(Ord
::cmp
)
2219 /// Returns the element that gives the maximum value from the
2220 /// specified function.
2222 /// If several elements are equally maximum, the last element is
2223 /// returned. If the iterator is empty, [`None`] is returned.
2225 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2230 /// let a = [-3_i32, 0, 1, 5, -10];
2231 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2234 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2235 fn max_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
2236 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
2239 fn key
<T
, B
>(mut f
: impl FnMut(&T
) -> B
) -> impl FnMut(T
) -> (B
, T
) {
2244 fn compare
<T
, B
: Ord
>((x_p
, _
): &(B
, T
), (y_p
, _
): &(B
, T
)) -> Ordering
{
2248 let (_
, x
) = self.map(key(f
)).max_by(compare
)?
;
2252 /// Returns the element that gives the maximum value with respect to the
2253 /// specified comparison function.
2255 /// If several elements are equally maximum, the last element is
2256 /// returned. If the iterator is empty, [`None`] is returned.
2258 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2263 /// let a = [-3_i32, 0, 1, 5, -10];
2264 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2267 #[stable(feature = "iter_max_by", since = "1.15.0")]
2268 fn max_by
<F
>(self, compare
: F
) -> Option
<Self::Item
>
2269 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2272 fn fold
<T
>(mut compare
: impl FnMut(&T
, &T
) -> Ordering
) -> impl FnMut(T
, T
) -> T
{
2273 move |x
, y
| cmp
::max_by(x
, y
, &mut compare
)
2276 fold1(self, fold(compare
))
2279 /// Returns the element that gives the minimum value from the
2280 /// specified function.
2282 /// If several elements are equally minimum, the first element is
2283 /// returned. If the iterator is empty, [`None`] is returned.
2285 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2290 /// let a = [-3_i32, 0, 1, 5, -10];
2291 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2294 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2295 fn min_by_key
<B
: Ord
, F
>(self, f
: F
) -> Option
<Self::Item
>
2296 where Self: Sized
, F
: FnMut(&Self::Item
) -> B
,
2299 fn key
<T
, B
>(mut f
: impl FnMut(&T
) -> B
) -> impl FnMut(T
) -> (B
, T
) {
2304 fn compare
<T
, B
: Ord
>((x_p
, _
): &(B
, T
), (y_p
, _
): &(B
, T
)) -> Ordering
{
2308 let (_
, x
) = self.map(key(f
)).min_by(compare
)?
;
2312 /// Returns the element that gives the minimum value with respect to the
2313 /// specified comparison function.
2315 /// If several elements are equally minimum, the first element is
2316 /// returned. If the iterator is empty, [`None`] is returned.
2318 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2323 /// let a = [-3_i32, 0, 1, 5, -10];
2324 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2327 #[stable(feature = "iter_min_by", since = "1.15.0")]
2328 fn min_by
<F
>(self, compare
: F
) -> Option
<Self::Item
>
2329 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
2332 fn fold
<T
>(mut compare
: impl FnMut(&T
, &T
) -> Ordering
) -> impl FnMut(T
, T
) -> T
{
2333 move |x
, y
| cmp
::min_by(x
, y
, &mut compare
)
2336 fold1(self, fold(compare
))
2340 /// Reverses an iterator's direction.
2342 /// Usually, iterators iterate from left to right. After using `rev()`,
2343 /// an iterator will instead iterate from right to left.
2345 /// This is only possible if the iterator has an end, so `rev()` only
2346 /// works on [`DoubleEndedIterator`]s.
2348 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2353 /// let a = [1, 2, 3];
2355 /// let mut iter = a.iter().rev();
2357 /// assert_eq!(iter.next(), Some(&3));
2358 /// assert_eq!(iter.next(), Some(&2));
2359 /// assert_eq!(iter.next(), Some(&1));
2361 /// assert_eq!(iter.next(), None);
2364 #[stable(feature = "rust1", since = "1.0.0")]
2365 fn rev(self) -> Rev
<Self> where Self: Sized
+ DoubleEndedIterator
{
2369 /// Converts an iterator of pairs into a pair of containers.
2371 /// `unzip()` consumes an entire iterator of pairs, producing two
2372 /// collections: one from the left elements of the pairs, and one
2373 /// from the right elements.
2375 /// This function is, in some sense, the opposite of [`zip`].
2377 /// [`zip`]: #method.zip
2384 /// let a = [(1, 2), (3, 4)];
2386 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2388 /// assert_eq!(left, [1, 3]);
2389 /// assert_eq!(right, [2, 4]);
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 fn unzip
<A
, B
, FromA
, FromB
>(self) -> (FromA
, FromB
) where
2393 FromA
: Default
+ Extend
<A
>,
2394 FromB
: Default
+ Extend
<B
>,
2395 Self: Sized
+ Iterator
<Item
=(A
, B
)>,
2397 fn extend
<'a
, A
, B
>(
2398 ts
: &'a
mut impl Extend
<A
>,
2399 us
: &'a
mut impl Extend
<B
>,
2400 ) -> impl FnMut((A
, B
)) + 'a
{
2407 let mut ts
: FromA
= Default
::default();
2408 let mut us
: FromB
= Default
::default();
2410 self.for_each(extend(&mut ts
, &mut us
));
2415 /// Creates an iterator which copies all of its elements.
2417 /// This is useful when you have an iterator over `&T`, but you need an
2418 /// iterator over `T`.
2425 /// let a = [1, 2, 3];
2427 /// let v_cloned: Vec<_> = a.iter().copied().collect();
2429 /// // copied is the same as .map(|&x| x)
2430 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2432 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2433 /// assert_eq!(v_map, vec![1, 2, 3]);
2435 #[stable(feature = "iter_copied", since = "1.36.0")]
2436 fn copied
<'a
, T
: 'a
>(self) -> Copied
<Self>
2437 where Self: Sized
+ Iterator
<Item
=&'a T
>, T
: Copy
2442 /// Creates an iterator which [`clone`]s all of its elements.
2444 /// This is useful when you have an iterator over `&T`, but you need an
2445 /// iterator over `T`.
2447 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2454 /// let a = [1, 2, 3];
2456 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2458 /// // cloned is the same as .map(|&x| x), for integers
2459 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2461 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2462 /// assert_eq!(v_map, vec![1, 2, 3]);
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 fn cloned
<'a
, T
: 'a
>(self) -> Cloned
<Self>
2466 where Self: Sized
+ Iterator
<Item
=&'a T
>, T
: Clone
2471 /// Repeats an iterator endlessly.
2473 /// Instead of stopping at [`None`], the iterator will instead start again,
2474 /// from the beginning. After iterating again, it will start at the
2475 /// beginning again. And again. And again. Forever.
2477 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2484 /// let a = [1, 2, 3];
2486 /// let mut it = a.iter().cycle();
2488 /// assert_eq!(it.next(), Some(&1));
2489 /// assert_eq!(it.next(), Some(&2));
2490 /// assert_eq!(it.next(), Some(&3));
2491 /// assert_eq!(it.next(), Some(&1));
2492 /// assert_eq!(it.next(), Some(&2));
2493 /// assert_eq!(it.next(), Some(&3));
2494 /// assert_eq!(it.next(), Some(&1));
2496 #[stable(feature = "rust1", since = "1.0.0")]
2498 fn cycle(self) -> Cycle
<Self> where Self: Sized
+ Clone
{
2502 /// Sums the elements of an iterator.
2504 /// Takes each element, adds them together, and returns the result.
2506 /// An empty iterator returns the zero value of the type.
2510 /// When calling `sum()` and a primitive integer type is being returned, this
2511 /// method will panic if the computation overflows and debug assertions are
2519 /// let a = [1, 2, 3];
2520 /// let sum: i32 = a.iter().sum();
2522 /// assert_eq!(sum, 6);
2524 #[stable(feature = "iter_arith", since = "1.11.0")]
2525 fn sum
<S
>(self) -> S
2532 /// Iterates over the entire iterator, multiplying all the elements
2534 /// An empty iterator returns the one value of the type.
2538 /// When calling `product()` and a primitive integer type is being returned,
2539 /// method will panic if the computation overflows and debug assertions are
2545 /// fn factorial(n: u32) -> u32 {
2546 /// (1..=n).product()
2548 /// assert_eq!(factorial(0), 1);
2549 /// assert_eq!(factorial(1), 1);
2550 /// assert_eq!(factorial(5), 120);
2552 #[stable(feature = "iter_arith", since = "1.11.0")]
2553 fn product
<P
>(self) -> P
2555 P
: Product
<Self::Item
>,
2557 Product
::product(self)
2560 /// Lexicographically compares the elements of this `Iterator` with those
2566 /// use std::cmp::Ordering;
2568 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2569 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2570 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2572 #[stable(feature = "iter_order", since = "1.5.0")]
2573 fn cmp
<I
>(self, other
: I
) -> Ordering
2575 I
: IntoIterator
<Item
= Self::Item
>,
2579 self.cmp_by(other
, |x
, y
| x
.cmp(&y
))
2582 /// Lexicographically compares the elements of this `Iterator` with those
2583 /// of another with respect to the specified comparison function.
2590 /// #![feature(iter_order_by)]
2592 /// use std::cmp::Ordering;
2594 /// let xs = [1, 2, 3, 4];
2595 /// let ys = [1, 4, 9, 16];
2597 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2598 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2599 /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2601 #[unstable(feature = "iter_order_by", issue = "64295")]
2602 fn cmp_by
<I
, F
>(mut self, other
: I
, mut cmp
: F
) -> Ordering
2606 F
: FnMut(Self::Item
, I
::Item
) -> Ordering
,
2608 let mut other
= other
.into_iter();
2611 let x
= match self.next() {
2612 None
=> if other
.next().is_none() {
2613 return Ordering
::Equal
2615 return Ordering
::Less
2620 let y
= match other
.next() {
2621 None
=> return Ordering
::Greater
,
2626 Ordering
::Equal
=> (),
2627 non_eq
=> return non_eq
,
2632 /// Lexicographically compares the elements of this `Iterator` with those
2638 /// use std::cmp::Ordering;
2640 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2641 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2642 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2644 /// assert_eq!([std::f64::NAN].iter().partial_cmp([1.].iter()), None);
2646 #[stable(feature = "iter_order", since = "1.5.0")]
2647 fn partial_cmp
<I
>(self, other
: I
) -> Option
<Ordering
>
2650 Self::Item
: PartialOrd
<I
::Item
>,
2653 self.partial_cmp_by(other
, |x
, y
| x
.partial_cmp(&y
))
2656 /// Lexicographically compares the elements of this `Iterator` with those
2657 /// of another with respect to the specified comparison function.
2664 /// #![feature(iter_order_by)]
2666 /// use std::cmp::Ordering;
2668 /// let xs = [1.0, 2.0, 3.0, 4.0];
2669 /// let ys = [1.0, 4.0, 9.0, 16.0];
2672 /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2673 /// Some(Ordering::Less)
2676 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2677 /// Some(Ordering::Equal)
2680 /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2681 /// Some(Ordering::Greater)
2684 #[unstable(feature = "iter_order_by", issue = "64295")]
2685 fn partial_cmp_by
<I
, F
>(mut self, other
: I
, mut partial_cmp
: F
) -> Option
<Ordering
>
2689 F
: FnMut(Self::Item
, I
::Item
) -> Option
<Ordering
>,
2691 let mut other
= other
.into_iter();
2694 let x
= match self.next() {
2695 None
=> if other
.next().is_none() {
2696 return Some(Ordering
::Equal
)
2698 return Some(Ordering
::Less
)
2703 let y
= match other
.next() {
2704 None
=> return Some(Ordering
::Greater
),
2708 match partial_cmp(x
, y
) {
2709 Some(Ordering
::Equal
) => (),
2710 non_eq
=> return non_eq
,
2715 /// Determines if the elements of this `Iterator` are equal to those of
2721 /// assert_eq!([1].iter().eq([1].iter()), true);
2722 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
2724 #[stable(feature = "iter_order", since = "1.5.0")]
2725 fn eq
<I
>(self, other
: I
) -> bool
2728 Self::Item
: PartialEq
<I
::Item
>,
2731 self.eq_by(other
, |x
, y
| x
== y
)
2734 /// Determines if the elements of this `Iterator` are equal to those of
2735 /// another with respect to the specified equality function.
2742 /// #![feature(iter_order_by)]
2744 /// let xs = [1, 2, 3, 4];
2745 /// let ys = [1, 4, 9, 16];
2747 /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
2749 #[unstable(feature = "iter_order_by", issue = "64295")]
2750 fn eq_by
<I
, F
>(mut self, other
: I
, mut eq
: F
) -> bool
2754 F
: FnMut(Self::Item
, I
::Item
) -> bool
,
2756 let mut other
= other
.into_iter();
2759 let x
= match self.next() {
2760 None
=> return other
.next().is_none(),
2764 let y
= match other
.next() {
2765 None
=> return false,
2775 /// Determines if the elements of this `Iterator` are unequal to those of
2781 /// assert_eq!([1].iter().ne([1].iter()), false);
2782 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
2784 #[stable(feature = "iter_order", since = "1.5.0")]
2785 fn ne
<I
>(self, other
: I
) -> bool
where
2787 Self::Item
: PartialEq
<I
::Item
>,
2793 /// Determines if the elements of this `Iterator` are lexicographically
2794 /// less than those of another.
2799 /// assert_eq!([1].iter().lt([1].iter()), false);
2800 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
2801 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
2803 #[stable(feature = "iter_order", since = "1.5.0")]
2804 fn lt
<I
>(self, other
: I
) -> bool
where
2806 Self::Item
: PartialOrd
<I
::Item
>,
2809 self.partial_cmp(other
) == Some(Ordering
::Less
)
2812 /// Determines if the elements of this `Iterator` are lexicographically
2813 /// less or equal to those of another.
2818 /// assert_eq!([1].iter().le([1].iter()), true);
2819 /// assert_eq!([1].iter().le([1, 2].iter()), true);
2820 /// assert_eq!([1, 2].iter().le([1].iter()), false);
2822 #[stable(feature = "iter_order", since = "1.5.0")]
2823 fn le
<I
>(self, other
: I
) -> bool
where
2825 Self::Item
: PartialOrd
<I
::Item
>,
2828 match self.partial_cmp(other
) {
2829 Some(Ordering
::Less
) | Some(Ordering
::Equal
) => true,
2834 /// Determines if the elements of this `Iterator` are lexicographically
2835 /// greater than those of another.
2840 /// assert_eq!([1].iter().gt([1].iter()), false);
2841 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
2842 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
2844 #[stable(feature = "iter_order", since = "1.5.0")]
2845 fn gt
<I
>(self, other
: I
) -> bool
where
2847 Self::Item
: PartialOrd
<I
::Item
>,
2850 self.partial_cmp(other
) == Some(Ordering
::Greater
)
2853 /// Determines if the elements of this `Iterator` are lexicographically
2854 /// greater than or equal to those of another.
2859 /// assert_eq!([1].iter().ge([1].iter()), true);
2860 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
2861 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
2863 #[stable(feature = "iter_order", since = "1.5.0")]
2864 fn ge
<I
>(self, other
: I
) -> bool
where
2866 Self::Item
: PartialOrd
<I
::Item
>,
2869 match self.partial_cmp(other
) {
2870 Some(Ordering
::Greater
) | Some(Ordering
::Equal
) => true,
2875 /// Checks if the elements of this iterator are sorted.
2877 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2878 /// iterator yields exactly zero or one element, `true` is returned.
2880 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2881 /// implies that this function returns `false` if any two consecutive items are not
2887 /// #![feature(is_sorted)]
2889 /// assert!([1, 2, 2, 9].iter().is_sorted());
2890 /// assert!(![1, 3, 2, 4].iter().is_sorted());
2891 /// assert!([0].iter().is_sorted());
2892 /// assert!(std::iter::empty::<i32>().is_sorted());
2893 /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
2896 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2897 fn is_sorted(self) -> bool
2900 Self::Item
: PartialOrd
,
2902 self.is_sorted_by(PartialOrd
::partial_cmp
)
2905 /// Checks if the elements of this iterator are sorted using the given comparator function.
2907 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2908 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2909 /// [`is_sorted`]; see its documentation for more information.
2914 /// #![feature(is_sorted)]
2916 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
2917 /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
2918 /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
2919 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
2920 /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
2923 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2924 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2925 fn is_sorted_by
<F
>(mut self, mut compare
: F
) -> bool
2928 F
: FnMut(&Self::Item
, &Self::Item
) -> Option
<Ordering
>
2930 let mut last
= match self.next() {
2932 None
=> return true,
2935 while let Some(curr
) = self.next() {
2936 if let Some(Ordering
::Greater
) | None
= compare(&last
, &curr
) {
2945 /// Checks if the elements of this iterator are sorted using the given key extraction
2948 /// Instead of comparing the iterator's elements directly, this function compares the keys of
2949 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
2950 /// its documentation for more information.
2952 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2957 /// #![feature(is_sorted)]
2959 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
2960 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
2963 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2964 fn is_sorted_by_key
<F
, K
>(self, f
: F
) -> bool
2967 F
: FnMut(Self::Item
) -> K
,
2970 self.map(f
).is_sorted()
2974 /// Fold an iterator without having to provide an initial value.
2976 fn fold1
<I
, F
>(mut it
: I
, f
: F
) -> Option
<I
::Item
>
2979 F
: FnMut(I
::Item
, I
::Item
) -> I
::Item
,
2981 // start with the first element as our selection. This avoids
2982 // having to use `Option`s inside the loop, translating to a
2983 // sizeable performance gain (6x in one case).
2984 let first
= it
.next()?
;
2985 Some(it
.fold(first
, f
))
2988 #[stable(feature = "rust1", since = "1.0.0")]
2989 impl<I
: Iterator
+ ?Sized
> Iterator
for &mut I
{
2990 type Item
= I
::Item
;
2991 fn next(&mut self) -> Option
<I
::Item
> { (**self).next() }
2992 fn size_hint(&self) -> (usize, Option
<usize>) { (**self).size_hint() }
2993 fn nth(&mut self, n
: usize) -> Option
<Self::Item
> {