1 use crate::cmp::Ordering;
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 evaluate the iterator until its [`next`] returns
205 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
206 /// times it called [`next`].
208 /// [`next`]: #tymethod.next
209 /// [`None`]: ../../std/option/enum.Option.html#variant.None
211 /// # Overflow Behavior
213 /// The method does no guarding against overflows, so counting elements of
214 /// an iterator with more than [`usize::MAX`] elements either produces the
215 /// wrong result or panics. If debug assertions are enabled, a panic is
220 /// This function might panic if the iterator has more than [`usize::MAX`]
223 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
230 /// let a = [1, 2, 3];
231 /// assert_eq!(a.iter().count(), 3);
233 /// let a = [1, 2, 3, 4, 5];
234 /// assert_eq!(a.iter().count(), 5);
237 #[rustc_inherit_overflow_checks]
238 #[stable(feature = "rust1", since = "1.0.0")]
239 fn count(self) -> usize where Self: Sized {
241 self.fold(0, |cnt, _| cnt + 1)
244 /// Consumes the iterator, returning the last element.
246 /// This method will evaluate the iterator until it returns [`None`]. While
247 /// doing so, it keeps track of the current element. After [`None`] is
248 /// returned, `last()` will then return the last element it saw.
250 /// [`None`]: ../../std/option/enum.Option.html#variant.None
257 /// let a = [1, 2, 3];
258 /// assert_eq!(a.iter().last(), Some(&3));
260 /// let a = [1, 2, 3, 4, 5];
261 /// assert_eq!(a.iter().last(), Some(&5));
264 #[stable(feature = "rust1", since = "1.0.0")]
265 fn last(self) -> Option<Self::Item> where Self: Sized {
267 for x in self { last = Some(x); }
271 /// Returns the `n`th element of the iterator.
273 /// Like most indexing operations, the count starts from zero, so `nth(0)`
274 /// returns the first value, `nth(1)` the second, and so on.
276 /// Note that all preceding elements, as well as the returned element, will be
277 /// consumed from the iterator. That means that the preceding elements will be
278 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
279 /// will return different elements.
281 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
284 /// [`None`]: ../../std/option/enum.Option.html#variant.None
291 /// let a = [1, 2, 3];
292 /// assert_eq!(a.iter().nth(1), Some(&2));
295 /// Calling `nth()` multiple times doesn't rewind the iterator:
298 /// let a = [1, 2, 3];
300 /// let mut iter = a.iter();
302 /// assert_eq!(iter.nth(1), Some(&2));
303 /// assert_eq!(iter.nth(1), None);
306 /// Returning `None` if there are less than `n + 1` elements:
309 /// let a = [1, 2, 3];
310 /// assert_eq!(a.iter().nth(10), None);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
316 if n == 0 { return Some(x) }
322 /// Creates an iterator starting at the same point, but stepping by
323 /// the given amount at each iteration.
325 /// Note 1: The first element of the iterator will always be returned,
326 /// regardless of the step given.
328 /// Note 2: The time at which ignored elements are pulled is not fixed.
329 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
330 /// but is also free to behave like the sequence
331 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
332 /// Which way is used may change for some iterators for performance reasons.
333 /// The second way will advance the iterator earlier and may consume more items.
335 /// `advance_n_and_return_first` is the equivalent of:
337 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
341 /// let next = iter.next();
342 /// if total_step > 1 {
343 /// iter.nth(total_step-2);
351 /// The method will panic if the given step is `0`.
358 /// let a = [0, 1, 2, 3, 4, 5];
359 /// let mut iter = a.into_iter().step_by(2);
361 /// assert_eq!(iter.next(), Some(&0));
362 /// assert_eq!(iter.next(), Some(&2));
363 /// assert_eq!(iter.next(), Some(&4));
364 /// assert_eq!(iter.next(), None);
367 #[stable(feature = "iterator_step_by", since = "1.28.0")]
368 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
369 StepBy::new(self, step)
372 /// Takes two iterators and creates a new iterator over both in sequence.
374 /// `chain()` will return a new iterator which will first iterate over
375 /// values from the first iterator and then over values from the second
378 /// In other words, it links two iterators together, in a chain. 🔗
385 /// let a1 = [1, 2, 3];
386 /// let a2 = [4, 5, 6];
388 /// let mut iter = a1.iter().chain(a2.iter());
390 /// assert_eq!(iter.next(), Some(&1));
391 /// assert_eq!(iter.next(), Some(&2));
392 /// assert_eq!(iter.next(), Some(&3));
393 /// assert_eq!(iter.next(), Some(&4));
394 /// assert_eq!(iter.next(), Some(&5));
395 /// assert_eq!(iter.next(), Some(&6));
396 /// assert_eq!(iter.next(), None);
399 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
400 /// anything that can be converted into an [`Iterator`], not just an
401 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
402 /// [`IntoIterator`], and so can be passed to `chain()` directly:
404 /// [`IntoIterator`]: trait.IntoIterator.html
405 /// [`Iterator`]: trait.Iterator.html
408 /// let s1 = &[1, 2, 3];
409 /// let s2 = &[4, 5, 6];
411 /// let mut iter = s1.iter().chain(s2);
413 /// assert_eq!(iter.next(), Some(&1));
414 /// assert_eq!(iter.next(), Some(&2));
415 /// assert_eq!(iter.next(), Some(&3));
416 /// assert_eq!(iter.next(), Some(&4));
417 /// assert_eq!(iter.next(), Some(&5));
418 /// assert_eq!(iter.next(), Some(&6));
419 /// assert_eq!(iter.next(), None);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
424 Self: Sized, U: IntoIterator<Item=Self::Item>,
426 Chain::new(self, other.into_iter())
429 /// 'Zips up' two iterators into a single iterator of pairs.
431 /// `zip()` returns a new iterator that will iterate over two other
432 /// iterators, returning a tuple where the first element comes from the
433 /// first iterator, and the second element comes from the second iterator.
435 /// In other words, it zips two iterators together, into a single one.
437 /// If either iterator returns [`None`], [`next`] from the zipped iterator
438 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
439 /// short-circuit and `next` will not be called on the second iterator.
446 /// let a1 = [1, 2, 3];
447 /// let a2 = [4, 5, 6];
449 /// let mut iter = a1.iter().zip(a2.iter());
451 /// assert_eq!(iter.next(), Some((&1, &4)));
452 /// assert_eq!(iter.next(), Some((&2, &5)));
453 /// assert_eq!(iter.next(), Some((&3, &6)));
454 /// assert_eq!(iter.next(), None);
457 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
458 /// anything that can be converted into an [`Iterator`], not just an
459 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
460 /// [`IntoIterator`], and so can be passed to `zip()` directly:
462 /// [`IntoIterator`]: trait.IntoIterator.html
463 /// [`Iterator`]: trait.Iterator.html
466 /// let s1 = &[1, 2, 3];
467 /// let s2 = &[4, 5, 6];
469 /// let mut iter = s1.iter().zip(s2);
471 /// assert_eq!(iter.next(), Some((&1, &4)));
472 /// assert_eq!(iter.next(), Some((&2, &5)));
473 /// assert_eq!(iter.next(), Some((&3, &6)));
474 /// assert_eq!(iter.next(), None);
477 /// `zip()` is often used to zip an infinite iterator to a finite one.
478 /// This works because the finite iterator will eventually return [`None`],
479 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
482 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
484 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
486 /// assert_eq!((0, 'f'), enumerate[0]);
487 /// assert_eq!((0, 'f'), zipper[0]);
489 /// assert_eq!((1, 'o'), enumerate[1]);
490 /// assert_eq!((1, 'o'), zipper[1]);
492 /// assert_eq!((2, 'o'), enumerate[2]);
493 /// assert_eq!((2, 'o'), zipper[2]);
496 /// [`enumerate`]: trait.Iterator.html#method.enumerate
497 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
498 /// [`None`]: ../../std/option/enum.Option.html#variant.None
500 #[stable(feature = "rust1", since = "1.0.0")]
501 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
502 Self: Sized, U: IntoIterator
504 Zip::new(self, other.into_iter())
507 /// Takes a closure and creates an iterator which calls that closure on each
510 /// `map()` transforms one iterator into another, by means of its argument:
511 /// something that implements [`FnMut`]. It produces a new iterator which
512 /// calls this closure on each element of the original iterator.
514 /// If you are good at thinking in types, you can think of `map()` like this:
515 /// If you have an iterator that gives you elements of some type `A`, and
516 /// you want an iterator of some other type `B`, you can use `map()`,
517 /// passing a closure that takes an `A` and returns a `B`.
519 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
520 /// lazy, it is best used when you're already working with other iterators.
521 /// If you're doing some sort of looping for a side effect, it's considered
522 /// more idiomatic to use [`for`] than `map()`.
524 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
525 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
532 /// let a = [1, 2, 3];
534 /// let mut iter = a.into_iter().map(|x| 2 * x);
536 /// assert_eq!(iter.next(), Some(2));
537 /// assert_eq!(iter.next(), Some(4));
538 /// assert_eq!(iter.next(), Some(6));
539 /// assert_eq!(iter.next(), None);
542 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
545 /// # #![allow(unused_must_use)]
546 /// // don't do this:
547 /// (0..5).map(|x| println!("{}", x));
549 /// // it won't even execute, as it is lazy. Rust will warn you about this.
551 /// // Instead, use for:
553 /// println!("{}", x);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 fn map<B, F>(self, f: F) -> Map<Self, F> where
559 Self: Sized, F: FnMut(Self::Item) -> B,
564 /// Calls a closure on each element of an iterator.
566 /// This is equivalent to using a [`for`] loop on the iterator, although
567 /// `break` and `continue` are not possible from a closure. It's generally
568 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
569 /// when processing items at the end of longer iterator chains. In some
570 /// cases `for_each` may also be faster than a loop, because it will use
571 /// internal iteration on adaptors like `Chain`.
573 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
580 /// use std::sync::mpsc::channel;
582 /// let (tx, rx) = channel();
583 /// (0..5).map(|x| x * 2 + 1)
584 /// .for_each(move |x| tx.send(x).unwrap());
586 /// let v: Vec<_> = rx.iter().collect();
587 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
590 /// For such a small example, a `for` loop may be cleaner, but `for_each`
591 /// might be preferable to keep a functional style with longer iterators:
594 /// (0..5).flat_map(|x| x * 100 .. x * 110)
596 /// .filter(|&(i, x)| (i + x) % 3 == 0)
597 /// .for_each(|(i, x)| println!("{}:{}", i, x));
600 #[stable(feature = "iterator_for_each", since = "1.21.0")]
601 fn for_each<F>(self, mut f: F) where
602 Self: Sized, F: FnMut(Self::Item),
604 self.fold((), move |(), item| f(item));
607 /// Creates an iterator which uses a closure to determine if an element
608 /// should be yielded.
610 /// The closure must return `true` or `false`. `filter()` creates an
611 /// iterator which calls this closure on each element. If the closure
612 /// returns `true`, then the element is returned. If the closure returns
613 /// `false`, it will try again, and call the closure on the next element,
614 /// seeing if it passes the test.
621 /// let a = [0i32, 1, 2];
623 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
625 /// assert_eq!(iter.next(), Some(&1));
626 /// assert_eq!(iter.next(), Some(&2));
627 /// assert_eq!(iter.next(), None);
630 /// Because the closure passed to `filter()` takes a reference, and many
631 /// iterators iterate over references, this leads to a possibly confusing
632 /// situation, where the type of the closure is a double reference:
635 /// let a = [0, 1, 2];
637 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
639 /// assert_eq!(iter.next(), Some(&2));
640 /// assert_eq!(iter.next(), None);
643 /// It's common to instead use destructuring on the argument to strip away
647 /// let a = [0, 1, 2];
649 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
651 /// assert_eq!(iter.next(), Some(&2));
652 /// assert_eq!(iter.next(), None);
658 /// let a = [0, 1, 2];
660 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
662 /// assert_eq!(iter.next(), Some(&2));
663 /// assert_eq!(iter.next(), None);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
670 Self: Sized, P: FnMut(&Self::Item) -> bool,
672 Filter::new(self, predicate)
675 /// Creates an iterator that both filters and maps.
677 /// The closure must return an [`Option<T>`]. `filter_map` creates an
678 /// iterator which calls this closure on each element. If the closure
679 /// returns [`Some(element)`][`Some`], then that element is returned. If the
680 /// closure returns [`None`], it will try again, and call the closure on the
681 /// next element, seeing if it will return [`Some`].
683 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
686 /// [`filter`]: #method.filter
687 /// [`map`]: #method.map
689 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
691 /// In other words, it removes the [`Option<T>`] layer automatically. If your
692 /// mapping is already returning an [`Option<T>`] and you want to skip over
693 /// [`None`]s, then `filter_map` is much, much nicer to use.
700 /// let a = ["1", "lol", "3", "NaN", "5"];
702 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
704 /// assert_eq!(iter.next(), Some(1));
705 /// assert_eq!(iter.next(), Some(3));
706 /// assert_eq!(iter.next(), Some(5));
707 /// assert_eq!(iter.next(), None);
710 /// Here's the same example, but with [`filter`] and [`map`]:
713 /// let a = ["1", "lol", "3", "NaN", "5"];
714 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
715 /// assert_eq!(iter.next(), Some(1));
716 /// assert_eq!(iter.next(), Some(3));
717 /// assert_eq!(iter.next(), Some(5));
718 /// assert_eq!(iter.next(), None);
721 /// [`Option<T>`]: ../../std/option/enum.Option.html
722 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
723 /// [`None`]: ../../std/option/enum.Option.html#variant.None
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
727 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
729 FilterMap::new(self, f)
732 /// Creates an iterator which gives the current iteration count as well as
735 /// The iterator returned yields pairs `(i, val)`, where `i` is the
736 /// current index of iteration and `val` is the value returned by the
739 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
740 /// different sized integer, the [`zip`] function provides similar
743 /// # Overflow Behavior
745 /// The method does no guarding against overflows, so enumerating more than
746 /// [`usize::MAX`] elements either produces the wrong result or panics. If
747 /// debug assertions are enabled, a panic is guaranteed.
751 /// The returned iterator might panic if the to-be-returned index would
752 /// overflow a [`usize`].
754 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
755 /// [`usize`]: ../../std/primitive.usize.html
756 /// [`zip`]: #method.zip
761 /// let a = ['a', 'b', 'c'];
763 /// let mut iter = a.iter().enumerate();
765 /// assert_eq!(iter.next(), Some((0, &'a')));
766 /// assert_eq!(iter.next(), Some((1, &'b')));
767 /// assert_eq!(iter.next(), Some((2, &'c')));
768 /// assert_eq!(iter.next(), None);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
776 /// Creates an iterator which can use `peek` to look at the next element of
777 /// the iterator without consuming it.
779 /// Adds a [`peek`] method to an iterator. See its documentation for
780 /// more information.
782 /// Note that the underlying iterator is still advanced when [`peek`] is
783 /// called for the first time: In order to retrieve the next element,
784 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
785 /// anything other than fetching the next value) of the [`next`] method
788 /// [`peek`]: struct.Peekable.html#method.peek
789 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
796 /// let xs = [1, 2, 3];
798 /// let mut iter = xs.iter().peekable();
800 /// // peek() lets us see into the future
801 /// assert_eq!(iter.peek(), Some(&&1));
802 /// assert_eq!(iter.next(), Some(&1));
804 /// assert_eq!(iter.next(), Some(&2));
806 /// // we can peek() multiple times, the iterator won't advance
807 /// assert_eq!(iter.peek(), Some(&&3));
808 /// assert_eq!(iter.peek(), Some(&&3));
810 /// assert_eq!(iter.next(), Some(&3));
812 /// // after the iterator is finished, so is peek()
813 /// assert_eq!(iter.peek(), None);
814 /// assert_eq!(iter.next(), None);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 fn peekable(self) -> Peekable<Self> where Self: Sized {
822 /// Creates an iterator that [`skip`]s elements based on a predicate.
824 /// [`skip`]: #method.skip
826 /// `skip_while()` takes a closure as an argument. It will call this
827 /// closure on each element of the iterator, and ignore elements
828 /// until it returns `false`.
830 /// After `false` is returned, `skip_while()`'s job is over, and the
831 /// rest of the elements are yielded.
838 /// let a = [-1i32, 0, 1];
840 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
842 /// assert_eq!(iter.next(), Some(&0));
843 /// assert_eq!(iter.next(), Some(&1));
844 /// assert_eq!(iter.next(), None);
847 /// Because the closure passed to `skip_while()` takes a reference, and many
848 /// iterators iterate over references, this leads to a possibly confusing
849 /// situation, where the type of the closure is a double reference:
852 /// let a = [-1, 0, 1];
854 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
856 /// assert_eq!(iter.next(), Some(&0));
857 /// assert_eq!(iter.next(), Some(&1));
858 /// assert_eq!(iter.next(), None);
861 /// Stopping after an initial `false`:
864 /// let a = [-1, 0, 1, -2];
866 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
868 /// assert_eq!(iter.next(), Some(&0));
869 /// assert_eq!(iter.next(), Some(&1));
871 /// // while this would have been false, since we already got a false,
872 /// // skip_while() isn't used any more
873 /// assert_eq!(iter.next(), Some(&-2));
875 /// assert_eq!(iter.next(), None);
878 #[stable(feature = "rust1", since = "1.0.0")]
879 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
880 Self: Sized, P: FnMut(&Self::Item) -> bool,
882 SkipWhile::new(self, predicate)
885 /// Creates an iterator that yields elements based on a predicate.
887 /// `take_while()` takes a closure as an argument. It will call this
888 /// closure on each element of the iterator, and yield elements
889 /// while it returns `true`.
891 /// After `false` is returned, `take_while()`'s job is over, and the
892 /// rest of the elements are ignored.
899 /// let a = [-1i32, 0, 1];
901 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
903 /// assert_eq!(iter.next(), Some(&-1));
904 /// assert_eq!(iter.next(), None);
907 /// Because the closure passed to `take_while()` takes a reference, and many
908 /// iterators iterate over references, this leads to a possibly confusing
909 /// situation, where the type of the closure is a double reference:
912 /// let a = [-1, 0, 1];
914 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
916 /// assert_eq!(iter.next(), Some(&-1));
917 /// assert_eq!(iter.next(), None);
920 /// Stopping after an initial `false`:
923 /// let a = [-1, 0, 1, -2];
925 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
927 /// assert_eq!(iter.next(), Some(&-1));
929 /// // We have more elements that are less than zero, but since we already
930 /// // got a false, take_while() isn't used any more
931 /// assert_eq!(iter.next(), None);
934 /// Because `take_while()` needs to look at the value in order to see if it
935 /// should be included or not, consuming iterators will see that it is
939 /// let a = [1, 2, 3, 4];
940 /// let mut iter = a.into_iter();
942 /// let result: Vec<i32> = iter.by_ref()
943 /// .take_while(|n| **n != 3)
947 /// assert_eq!(result, &[1, 2]);
949 /// let result: Vec<i32> = iter.cloned().collect();
951 /// assert_eq!(result, &[4]);
954 /// The `3` is no longer there, because it was consumed in order to see if
955 /// the iteration should stop, but wasn't placed back into the iterator.
957 #[stable(feature = "rust1", since = "1.0.0")]
958 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
959 Self: Sized, P: FnMut(&Self::Item) -> bool,
961 TakeWhile::new(self, predicate)
964 /// Creates an iterator that skips the first `n` elements.
966 /// After they have been consumed, the rest of the elements are yielded.
967 /// Rather than overriding this method directly, instead override the `nth` method.
974 /// let a = [1, 2, 3];
976 /// let mut iter = a.iter().skip(2);
978 /// assert_eq!(iter.next(), Some(&3));
979 /// assert_eq!(iter.next(), None);
982 #[stable(feature = "rust1", since = "1.0.0")]
983 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
987 /// Creates an iterator that yields its first `n` elements.
994 /// let a = [1, 2, 3];
996 /// let mut iter = a.iter().take(2);
998 /// assert_eq!(iter.next(), Some(&1));
999 /// assert_eq!(iter.next(), Some(&2));
1000 /// assert_eq!(iter.next(), None);
1003 /// `take()` is often used with an infinite iterator, to make it finite:
1006 /// let mut iter = (0..).take(3);
1008 /// assert_eq!(iter.next(), Some(0));
1009 /// assert_eq!(iter.next(), Some(1));
1010 /// assert_eq!(iter.next(), Some(2));
1011 /// assert_eq!(iter.next(), None);
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1019 /// An iterator adaptor similar to [`fold`] that holds internal state and
1020 /// produces a new iterator.
1022 /// [`fold`]: #method.fold
1024 /// `scan()` takes two arguments: an initial value which seeds the internal
1025 /// state, and a closure with two arguments, the first being a mutable
1026 /// reference to the internal state and the second an iterator element.
1027 /// The closure can assign to the internal state to share state between
1030 /// On iteration, the closure will be applied to each element of the
1031 /// iterator and the return value from the closure, an [`Option`], is
1032 /// yielded by the iterator.
1034 /// [`Option`]: ../../std/option/enum.Option.html
1041 /// let a = [1, 2, 3];
1043 /// let mut iter = a.iter().scan(1, |state, &x| {
1044 /// // each iteration, we'll multiply the state by the element
1045 /// *state = *state * x;
1047 /// // then, we'll yield the negation of the state
1051 /// assert_eq!(iter.next(), Some(-1));
1052 /// assert_eq!(iter.next(), Some(-2));
1053 /// assert_eq!(iter.next(), Some(-6));
1054 /// assert_eq!(iter.next(), None);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1059 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1061 Scan::new(self, initial_state, f)
1064 /// Creates an iterator that works like map, but flattens nested structure.
1066 /// The [`map`] adapter is very useful, but only when the closure
1067 /// argument produces values. If it produces an iterator instead, there's
1068 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1071 /// You can think of `flat_map(f)` as the semantic equivalent
1072 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1074 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1075 /// one item for each element, and `flat_map()`'s closure returns an
1076 /// iterator for each element.
1078 /// [`map`]: #method.map
1079 /// [`flatten`]: #method.flatten
1086 /// let words = ["alpha", "beta", "gamma"];
1088 /// // chars() returns an iterator
1089 /// let merged: String = words.iter()
1090 /// .flat_map(|s| s.chars())
1092 /// assert_eq!(merged, "alphabetagamma");
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1097 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1099 FlatMap::new(self, f)
1102 /// Creates an iterator that flattens nested structure.
1104 /// This is useful when you have an iterator of iterators or an iterator of
1105 /// things that can be turned into iterators and you want to remove one
1106 /// level of indirection.
1113 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1114 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1115 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1118 /// Mapping and then flattening:
1121 /// let words = ["alpha", "beta", "gamma"];
1123 /// // chars() returns an iterator
1124 /// let merged: String = words.iter()
1125 /// .map(|s| s.chars())
1128 /// assert_eq!(merged, "alphabetagamma");
1131 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1132 /// in this case since it conveys intent more clearly:
1135 /// let words = ["alpha", "beta", "gamma"];
1137 /// // chars() returns an iterator
1138 /// let merged: String = words.iter()
1139 /// .flat_map(|s| s.chars())
1141 /// assert_eq!(merged, "alphabetagamma");
1144 /// Flattening once only removes one level of nesting:
1147 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1149 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1150 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1152 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1153 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1156 /// Here we see that `flatten()` does not perform a "deep" flatten.
1157 /// Instead, only one level of nesting is removed. That is, if you
1158 /// `flatten()` a three-dimensional array the result will be
1159 /// two-dimensional and not one-dimensional. To get a one-dimensional
1160 /// structure, you have to `flatten()` again.
1162 /// [`flat_map()`]: #method.flat_map
1164 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1165 fn flatten(self) -> Flatten<Self>
1166 where Self: Sized, Self::Item: IntoIterator {
1170 /// Creates an iterator which ends after the first [`None`].
1172 /// After an iterator returns [`None`], future calls may or may not yield
1173 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1174 /// [`None`] is given, it will always return [`None`] forever.
1176 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1177 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1184 /// // an iterator which alternates between Some and None
1185 /// struct Alternate {
1189 /// impl Iterator for Alternate {
1190 /// type Item = i32;
1192 /// fn next(&mut self) -> Option<i32> {
1193 /// let val = self.state;
1194 /// self.state = self.state + 1;
1196 /// // if it's even, Some(i32), else None
1197 /// if val % 2 == 0 {
1205 /// let mut iter = Alternate { state: 0 };
1207 /// // we can see our iterator going back and forth
1208 /// assert_eq!(iter.next(), Some(0));
1209 /// assert_eq!(iter.next(), None);
1210 /// assert_eq!(iter.next(), Some(2));
1211 /// assert_eq!(iter.next(), None);
1213 /// // however, once we fuse it...
1214 /// let mut iter = iter.fuse();
1216 /// assert_eq!(iter.next(), Some(4));
1217 /// assert_eq!(iter.next(), None);
1219 /// // it will always return `None` after the first time.
1220 /// assert_eq!(iter.next(), None);
1221 /// assert_eq!(iter.next(), None);
1222 /// assert_eq!(iter.next(), None);
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 fn fuse(self) -> Fuse<Self> where Self: Sized {
1230 /// Do something with each element of an iterator, passing the value on.
1232 /// When using iterators, you'll often chain several of them together.
1233 /// While working on such code, you might want to check out what's
1234 /// happening at various parts in the pipeline. To do that, insert
1235 /// a call to `inspect()`.
1237 /// It's more common for `inspect()` to be used as a debugging tool than to
1238 /// exist in your final code, but applications may find it useful in certain
1239 /// situations when errors need to be logged before being discarded.
1246 /// let a = [1, 4, 2, 3];
1248 /// // this iterator sequence is complex.
1249 /// let sum = a.iter()
1251 /// .filter(|x| x % 2 == 0)
1252 /// .fold(0, |sum, i| sum + i);
1254 /// println!("{}", sum);
1256 /// // let's add some inspect() calls to investigate what's happening
1257 /// let sum = a.iter()
1259 /// .inspect(|x| println!("about to filter: {}", x))
1260 /// .filter(|x| x % 2 == 0)
1261 /// .inspect(|x| println!("made it through filter: {}", x))
1262 /// .fold(0, |sum, i| sum + i);
1264 /// println!("{}", sum);
1267 /// This will print:
1271 /// about to filter: 1
1272 /// about to filter: 4
1273 /// made it through filter: 4
1274 /// about to filter: 2
1275 /// made it through filter: 2
1276 /// about to filter: 3
1280 /// Logging errors before discarding them:
1283 /// let lines = ["1", "2", "a"];
1285 /// let sum: i32 = lines
1287 /// .map(|line| line.parse::<i32>())
1288 /// .inspect(|num| {
1289 /// if let Err(ref e) = *num {
1290 /// println!("Parsing error: {}", e);
1293 /// .filter_map(Result::ok)
1296 /// println!("Sum: {}", sum);
1299 /// This will print:
1302 /// Parsing error: invalid digit found in string
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1308 Self: Sized, F: FnMut(&Self::Item),
1310 Inspect::new(self, f)
1313 /// Borrows an iterator, rather than consuming it.
1315 /// This is useful to allow applying iterator adaptors while still
1316 /// retaining ownership of the original iterator.
1323 /// let a = [1, 2, 3];
1325 /// let iter = a.into_iter();
1327 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1329 /// assert_eq!(sum, 6);
1331 /// // if we try to use iter again, it won't work. The following line
1332 /// // gives "error: use of moved value: `iter`
1333 /// // assert_eq!(iter.next(), None);
1335 /// // let's try that again
1336 /// let a = [1, 2, 3];
1338 /// let mut iter = a.into_iter();
1340 /// // instead, we add in a .by_ref()
1341 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1343 /// assert_eq!(sum, 3);
1345 /// // now this is just fine:
1346 /// assert_eq!(iter.next(), Some(&3));
1347 /// assert_eq!(iter.next(), None);
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1352 /// Transforms an iterator into a collection.
1354 /// `collect()` can take anything iterable, and turn it into a relevant
1355 /// collection. This is one of the more powerful methods in the standard
1356 /// library, used in a variety of contexts.
1358 /// The most basic pattern in which `collect()` is used is to turn one
1359 /// collection into another. You take a collection, call [`iter`] on it,
1360 /// do a bunch of transformations, and then `collect()` at the end.
1362 /// One of the keys to `collect()`'s power is that many things you might
1363 /// not think of as 'collections' actually are. For example, a [`String`]
1364 /// is a collection of [`char`]s. And a collection of
1365 /// [`Result<T, E>`][`Result`] can be thought of as single
1366 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1368 /// Because `collect()` is so general, it can cause problems with type
1369 /// inference. As such, `collect()` is one of the few times you'll see
1370 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1371 /// helps the inference algorithm understand specifically which collection
1372 /// you're trying to collect into.
1379 /// let a = [1, 2, 3];
1381 /// let doubled: Vec<i32> = a.iter()
1382 /// .map(|&x| x * 2)
1385 /// assert_eq!(vec![2, 4, 6], doubled);
1388 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1389 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1391 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1394 /// use std::collections::VecDeque;
1396 /// let a = [1, 2, 3];
1398 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1400 /// assert_eq!(2, doubled[0]);
1401 /// assert_eq!(4, doubled[1]);
1402 /// assert_eq!(6, doubled[2]);
1405 /// Using the 'turbofish' instead of annotating `doubled`:
1408 /// let a = [1, 2, 3];
1410 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1412 /// assert_eq!(vec![2, 4, 6], doubled);
1415 /// Because `collect()` only cares about what you're collecting into, you can
1416 /// still use a partial type hint, `_`, with the turbofish:
1419 /// let a = [1, 2, 3];
1421 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1423 /// assert_eq!(vec![2, 4, 6], doubled);
1426 /// Using `collect()` to make a [`String`]:
1429 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1431 /// let hello: String = chars.iter()
1432 /// .map(|&x| x as u8)
1433 /// .map(|x| (x + 1) as char)
1436 /// assert_eq!("hello", hello);
1439 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1440 /// see if any of them failed:
1443 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1445 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1447 /// // gives us the first error
1448 /// assert_eq!(Err("nope"), result);
1450 /// let results = [Ok(1), Ok(3)];
1452 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1454 /// // gives us the list of answers
1455 /// assert_eq!(Ok(vec![1, 3]), result);
1458 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1459 /// [`String`]: ../../std/string/struct.String.html
1460 /// [`char`]: ../../std/primitive.char.html
1461 /// [`Result`]: ../../std/result/enum.Result.html
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1465 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1466 FromIterator::from_iter(self)
1469 /// Consumes an iterator, creating two collections from it.
1471 /// The predicate passed to `partition()` can return `true`, or `false`.
1472 /// `partition()` returns a pair, all of the elements for which it returned
1473 /// `true`, and all of the elements for which it returned `false`.
1480 /// let a = [1, 2, 3];
1482 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1484 /// .partition(|&n| n % 2 == 0);
1486 /// assert_eq!(even, vec![2]);
1487 /// assert_eq!(odd, vec![1, 3]);
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 fn partition<B, F>(self, mut f: F) -> (B, B) where
1492 B: Default + Extend<Self::Item>,
1493 F: FnMut(&Self::Item) -> bool
1495 let mut left: B = Default::default();
1496 let mut right: B = Default::default();
1500 left.extend(Some(x))
1502 right.extend(Some(x))
1509 /// An iterator method that applies a function as long as it returns
1510 /// successfully, producing a single, final value.
1512 /// `try_fold()` takes two arguments: an initial value, and a closure with
1513 /// two arguments: an 'accumulator', and an element. The closure either
1514 /// returns successfully, with the value that the accumulator should have
1515 /// for the next iteration, or it returns failure, with an error value that
1516 /// is propagated back to the caller immediately (short-circuiting).
1518 /// The initial value is the value the accumulator will have on the first
1519 /// call. If applying the closure succeeded against every element of the
1520 /// iterator, `try_fold()` returns the final accumulator as success.
1522 /// Folding is useful whenever you have a collection of something, and want
1523 /// to produce a single value from it.
1525 /// # Note to Implementors
1527 /// Most of the other (forward) methods have default implementations in
1528 /// terms of this one, so try to implement this explicitly if it can
1529 /// do something better than the default `for` loop implementation.
1531 /// In particular, try to have this call `try_fold()` on the internal parts
1532 /// from which this iterator is composed. If multiple calls are needed,
1533 /// the `?` operator may be convenient for chaining the accumulator value
1534 /// along, but beware any invariants that need to be upheld before those
1535 /// early returns. This is a `&mut self` method, so iteration needs to be
1536 /// resumable after hitting an error here.
1543 /// let a = [1, 2, 3];
1545 /// // the checked sum of all of the elements of the array
1546 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1548 /// assert_eq!(sum, Some(6));
1551 /// Short-circuiting:
1554 /// let a = [10, 20, 30, 100, 40, 50];
1555 /// let mut it = a.iter();
1557 /// // This sum overflows when adding the 100 element
1558 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1559 /// assert_eq!(sum, None);
1561 /// // Because it short-circuited, the remaining elements are still
1562 /// // available through the iterator.
1563 /// assert_eq!(it.len(), 2);
1564 /// assert_eq!(it.next(), Some(&40));
1567 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1568 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1569 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1571 let mut accum = init;
1572 while let Some(x) = self.next() {
1573 accum = f(accum, x)?;
1578 /// An iterator method that applies a fallible function to each item in the
1579 /// iterator, stopping at the first error and returning that error.
1581 /// This can also be thought of as the fallible form of [`for_each()`]
1582 /// or as the stateless version of [`try_fold()`].
1584 /// [`for_each()`]: #method.for_each
1585 /// [`try_fold()`]: #method.try_fold
1590 /// use std::fs::rename;
1591 /// use std::io::{stdout, Write};
1592 /// use std::path::Path;
1594 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1596 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1597 /// assert!(res.is_ok());
1599 /// let mut it = data.iter().cloned();
1600 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1601 /// assert!(res.is_err());
1602 /// // It short-circuited, so the remaining items are still in the iterator:
1603 /// assert_eq!(it.next(), Some("stale_bread.json"));
1606 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1607 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1608 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1610 self.try_fold((), move |(), x| f(x))
1613 /// An iterator method that applies a function, producing a single, final value.
1615 /// `fold()` takes two arguments: an initial value, and a closure with two
1616 /// arguments: an 'accumulator', and an element. The closure returns the value that
1617 /// the accumulator should have for the next iteration.
1619 /// The initial value is the value the accumulator will have on the first
1622 /// After applying this closure to every element of the iterator, `fold()`
1623 /// returns the accumulator.
1625 /// This operation is sometimes called 'reduce' or 'inject'.
1627 /// Folding is useful whenever you have a collection of something, and want
1628 /// to produce a single value from it.
1630 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1631 /// may not terminate for infinite iterators, even on traits for which a
1632 /// result is determinable in finite time.
1639 /// let a = [1, 2, 3];
1641 /// // the sum of all of the elements of the array
1642 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1644 /// assert_eq!(sum, 6);
1647 /// Let's walk through each step of the iteration here:
1649 /// | element | acc | x | result |
1650 /// |---------|-----|---|--------|
1652 /// | 1 | 0 | 1 | 1 |
1653 /// | 2 | 1 | 2 | 3 |
1654 /// | 3 | 3 | 3 | 6 |
1656 /// And so, our final result, `6`.
1658 /// It's common for people who haven't used iterators a lot to
1659 /// use a `for` loop with a list of things to build up a result. Those
1660 /// can be turned into `fold()`s:
1662 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1665 /// let numbers = [1, 2, 3, 4, 5];
1667 /// let mut result = 0;
1670 /// for i in &numbers {
1671 /// result = result + i;
1675 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1677 /// // they're the same
1678 /// assert_eq!(result, result2);
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1683 Self: Sized, F: FnMut(B, Self::Item) -> B,
1685 self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1688 /// Tests if every element of the iterator matches a predicate.
1690 /// `all()` takes a closure that returns `true` or `false`. It applies
1691 /// this closure to each element of the iterator, and if they all return
1692 /// `true`, then so does `all()`. If any of them return `false`, it
1693 /// returns `false`.
1695 /// `all()` is short-circuiting; in other words, it will stop processing
1696 /// as soon as it finds a `false`, given that no matter what else happens,
1697 /// the result will also be `false`.
1699 /// An empty iterator returns `true`.
1706 /// let a = [1, 2, 3];
1708 /// assert!(a.iter().all(|&x| x > 0));
1710 /// assert!(!a.iter().all(|&x| x > 2));
1713 /// Stopping at the first `false`:
1716 /// let a = [1, 2, 3];
1718 /// let mut iter = a.iter();
1720 /// assert!(!iter.all(|&x| x != 2));
1722 /// // we can still use `iter`, as there are more elements.
1723 /// assert_eq!(iter.next(), Some(&3));
1726 #[stable(feature = "rust1", since = "1.0.0")]
1727 fn all<F>(&mut self, mut f: F) -> bool where
1728 Self: Sized, F: FnMut(Self::Item) -> bool
1730 self.try_for_each(move |x| {
1731 if f(x) { LoopState::Continue(()) }
1732 else { LoopState::Break(()) }
1733 }) == LoopState::Continue(())
1736 /// Tests if any element of the iterator matches a predicate.
1738 /// `any()` takes a closure that returns `true` or `false`. It applies
1739 /// this closure to each element of the iterator, and if any of them return
1740 /// `true`, then so does `any()`. If they all return `false`, it
1741 /// returns `false`.
1743 /// `any()` is short-circuiting; in other words, it will stop processing
1744 /// as soon as it finds a `true`, given that no matter what else happens,
1745 /// the result will also be `true`.
1747 /// An empty iterator returns `false`.
1754 /// let a = [1, 2, 3];
1756 /// assert!(a.iter().any(|&x| x > 0));
1758 /// assert!(!a.iter().any(|&x| x > 5));
1761 /// Stopping at the first `true`:
1764 /// let a = [1, 2, 3];
1766 /// let mut iter = a.iter();
1768 /// assert!(iter.any(|&x| x != 2));
1770 /// // we can still use `iter`, as there are more elements.
1771 /// assert_eq!(iter.next(), Some(&2));
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 fn any<F>(&mut self, mut f: F) -> bool where
1777 F: FnMut(Self::Item) -> bool
1779 self.try_for_each(move |x| {
1780 if f(x) { LoopState::Break(()) }
1781 else { LoopState::Continue(()) }
1782 }) == LoopState::Break(())
1785 /// Searches for an element of an iterator that satisfies a predicate.
1787 /// `find()` takes a closure that returns `true` or `false`. It applies
1788 /// this closure to each element of the iterator, and if any of them return
1789 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1790 /// `false`, it returns [`None`].
1792 /// `find()` is short-circuiting; in other words, it will stop processing
1793 /// as soon as the closure returns `true`.
1795 /// Because `find()` takes a reference, and many iterators iterate over
1796 /// references, this leads to a possibly confusing situation where the
1797 /// argument is a double reference. You can see this effect in the
1798 /// examples below, with `&&x`.
1800 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1801 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1808 /// let a = [1, 2, 3];
1810 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1812 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1815 /// Stopping at the first `true`:
1818 /// let a = [1, 2, 3];
1820 /// let mut iter = a.iter();
1822 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1824 /// // we can still use `iter`, as there are more elements.
1825 /// assert_eq!(iter.next(), Some(&3));
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1831 P: FnMut(&Self::Item) -> bool,
1833 self.try_for_each(move |x| {
1834 if predicate(&x) { LoopState::Break(x) }
1835 else { LoopState::Continue(()) }
1839 /// Applies function to the elements of iterator and returns
1840 /// the first non-none result.
1842 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1848 /// let a = ["lol", "NaN", "2", "5"];
1850 /// let first_number = a.iter().find_map(|s| s.parse().ok());
1852 /// assert_eq!(first_number, Some(2));
1855 #[stable(feature = "iterator_find_map", since = "1.30.0")]
1856 fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1858 F: FnMut(Self::Item) -> Option<B>,
1860 self.try_for_each(move |x| {
1862 Some(x) => LoopState::Break(x),
1863 None => LoopState::Continue(()),
1868 /// Searches for an element in an iterator, returning its index.
1870 /// `position()` takes a closure that returns `true` or `false`. It applies
1871 /// this closure to each element of the iterator, and if one of them
1872 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1873 /// them return `false`, it returns [`None`].
1875 /// `position()` is short-circuiting; in other words, it will stop
1876 /// processing as soon as it finds a `true`.
1878 /// # Overflow Behavior
1880 /// The method does no guarding against overflows, so if there are more
1881 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1882 /// result or panics. If debug assertions are enabled, a panic is
1887 /// This function might panic if the iterator has more than `usize::MAX`
1888 /// non-matching elements.
1890 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1891 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1892 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1899 /// let a = [1, 2, 3];
1901 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1903 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1906 /// Stopping at the first `true`:
1909 /// let a = [1, 2, 3, 4];
1911 /// let mut iter = a.iter();
1913 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1915 /// // we can still use `iter`, as there are more elements.
1916 /// assert_eq!(iter.next(), Some(&3));
1918 /// // The returned index depends on iterator state
1919 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1923 #[rustc_inherit_overflow_checks]
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1927 P: FnMut(Self::Item) -> bool,
1929 // The addition might panic on overflow
1930 self.try_fold(0, move |i, x| {
1931 if predicate(x) { LoopState::Break(i) }
1932 else { LoopState::Continue(i + 1) }
1936 /// Searches for an element in an iterator from the right, returning its
1939 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1940 /// this closure to each element of the iterator, starting from the end,
1941 /// and if one of them returns `true`, then `rposition()` returns
1942 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1944 /// `rposition()` is short-circuiting; in other words, it will stop
1945 /// processing as soon as it finds a `true`.
1947 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1948 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1955 /// let a = [1, 2, 3];
1957 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1959 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1962 /// Stopping at the first `true`:
1965 /// let a = [1, 2, 3];
1967 /// let mut iter = a.iter();
1969 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1971 /// // we can still use `iter`, as there are more elements.
1972 /// assert_eq!(iter.next(), Some(&1));
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1977 P: FnMut(Self::Item) -> bool,
1978 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1980 // No need for an overflow check here, because `ExactSizeIterator`
1981 // implies that the number of elements fits into a `usize`.
1983 self.try_rfold(n, move |i, x| {
1985 if predicate(x) { LoopState::Break(i) }
1986 else { LoopState::Continue(i) }
1990 /// Returns the maximum element of an iterator.
1992 /// If several elements are equally maximum, the last element is
1993 /// returned. If the iterator is empty, [`None`] is returned.
1995 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2002 /// let a = [1, 2, 3];
2003 /// let b: Vec<u32> = Vec::new();
2005 /// assert_eq!(a.iter().max(), Some(&3));
2006 /// assert_eq!(b.iter().max(), None);
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2012 self.max_by(Ord::cmp)
2015 /// Returns the minimum element of an iterator.
2017 /// If several elements are equally minimum, the first element is
2018 /// returned. If the iterator is empty, [`None`] is returned.
2020 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2027 /// let a = [1, 2, 3];
2028 /// let b: Vec<u32> = Vec::new();
2030 /// assert_eq!(a.iter().min(), Some(&1));
2031 /// assert_eq!(b.iter().min(), None);
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2037 self.min_by(Ord::cmp)
2040 /// Returns the element that gives the maximum value from the
2041 /// specified function.
2043 /// If several elements are equally maximum, the last element is
2044 /// returned. If the iterator is empty, [`None`] is returned.
2046 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2051 /// let a = [-3_i32, 0, 1, 5, -10];
2052 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2055 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2056 fn max_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2057 where Self: Sized, F: FnMut(&Self::Item) -> B,
2059 // switch to y even if it is only equal, to preserve stability.
2060 select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p <= y_p).map(|(_, x)| x)
2063 /// Returns the element that gives the maximum value with respect to the
2064 /// specified comparison function.
2066 /// If several elements are equally maximum, the last element is
2067 /// returned. If the iterator is empty, [`None`] is returned.
2069 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2074 /// let a = [-3_i32, 0, 1, 5, -10];
2075 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2078 #[stable(feature = "iter_max_by", since = "1.15.0")]
2079 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2080 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2082 // switch to y even if it is only equal, to preserve stability.
2083 select_fold1(self, |x, y| compare(x, y) != Ordering::Greater)
2086 /// Returns the element that gives the minimum value from the
2087 /// specified function.
2089 /// If several elements are equally minimum, the first element is
2090 /// returned. If the iterator is empty, [`None`] is returned.
2092 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2097 /// let a = [-3_i32, 0, 1, 5, -10];
2098 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2100 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2101 fn min_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2102 where Self: Sized, F: FnMut(&Self::Item) -> B,
2104 // only switch to y if it is strictly smaller, to preserve stability.
2105 select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p > y_p).map(|(_, x)| x)
2108 /// Returns the element that gives the minimum value with respect to the
2109 /// specified comparison function.
2111 /// If several elements are equally minimum, the first element is
2112 /// returned. If the iterator is empty, [`None`] is returned.
2114 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2119 /// let a = [-3_i32, 0, 1, 5, -10];
2120 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2123 #[stable(feature = "iter_min_by", since = "1.15.0")]
2124 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2125 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2127 // only switch to y if it is strictly smaller, to preserve stability.
2128 select_fold1(self, |x, y| compare(x, y) == Ordering::Greater)
2132 /// Reverses an iterator's direction.
2134 /// Usually, iterators iterate from left to right. After using `rev()`,
2135 /// an iterator will instead iterate from right to left.
2137 /// This is only possible if the iterator has an end, so `rev()` only
2138 /// works on [`DoubleEndedIterator`]s.
2140 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2145 /// let a = [1, 2, 3];
2147 /// let mut iter = a.iter().rev();
2149 /// assert_eq!(iter.next(), Some(&3));
2150 /// assert_eq!(iter.next(), Some(&2));
2151 /// assert_eq!(iter.next(), Some(&1));
2153 /// assert_eq!(iter.next(), None);
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2161 /// Converts an iterator of pairs into a pair of containers.
2163 /// `unzip()` consumes an entire iterator of pairs, producing two
2164 /// collections: one from the left elements of the pairs, and one
2165 /// from the right elements.
2167 /// This function is, in some sense, the opposite of [`zip`].
2169 /// [`zip`]: #method.zip
2176 /// let a = [(1, 2), (3, 4)];
2178 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2180 /// assert_eq!(left, [1, 3]);
2181 /// assert_eq!(right, [2, 4]);
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2185 FromA: Default + Extend<A>,
2186 FromB: Default + Extend<B>,
2187 Self: Sized + Iterator<Item=(A, B)>,
2189 let mut ts: FromA = Default::default();
2190 let mut us: FromB = Default::default();
2192 self.for_each(|(t, u)| {
2200 /// Creates an iterator which copies all of its elements.
2202 /// This is useful when you have an iterator over `&T`, but you need an
2203 /// iterator over `T`.
2210 /// let a = [1, 2, 3];
2212 /// let v_cloned: Vec<_> = a.iter().copied().collect();
2214 /// // copied is the same as .map(|&x| x)
2215 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2217 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2218 /// assert_eq!(v_map, vec![1, 2, 3]);
2220 #[stable(feature = "iter_copied", since = "1.36.0")]
2221 fn copied<'a, T: 'a>(self) -> Copied<Self>
2222 where Self: Sized + Iterator<Item=&'a T>, T: Copy
2227 /// Creates an iterator which [`clone`]s all of its elements.
2229 /// This is useful when you have an iterator over `&T`, but you need an
2230 /// iterator over `T`.
2232 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2239 /// let a = [1, 2, 3];
2241 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2243 /// // cloned is the same as .map(|&x| x), for integers
2244 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2246 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2247 /// assert_eq!(v_map, vec![1, 2, 3]);
2249 #[stable(feature = "rust1", since = "1.0.0")]
2250 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2251 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2256 /// Repeats an iterator endlessly.
2258 /// Instead of stopping at [`None`], the iterator will instead start again,
2259 /// from the beginning. After iterating again, it will start at the
2260 /// beginning again. And again. And again. Forever.
2262 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2269 /// let a = [1, 2, 3];
2271 /// let mut it = a.iter().cycle();
2273 /// assert_eq!(it.next(), Some(&1));
2274 /// assert_eq!(it.next(), Some(&2));
2275 /// assert_eq!(it.next(), Some(&3));
2276 /// assert_eq!(it.next(), Some(&1));
2277 /// assert_eq!(it.next(), Some(&2));
2278 /// assert_eq!(it.next(), Some(&3));
2279 /// assert_eq!(it.next(), Some(&1));
2281 #[stable(feature = "rust1", since = "1.0.0")]
2283 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2287 /// Sums the elements of an iterator.
2289 /// Takes each element, adds them together, and returns the result.
2291 /// An empty iterator returns the zero value of the type.
2295 /// When calling `sum()` and a primitive integer type is being returned, this
2296 /// method will panic if the computation overflows and debug assertions are
2304 /// let a = [1, 2, 3];
2305 /// let sum: i32 = a.iter().sum();
2307 /// assert_eq!(sum, 6);
2309 #[stable(feature = "iter_arith", since = "1.11.0")]
2310 fn sum<S>(self) -> S
2317 /// Iterates over the entire iterator, multiplying all the elements
2319 /// An empty iterator returns the one value of the type.
2323 /// When calling `product()` and a primitive integer type is being returned,
2324 /// method will panic if the computation overflows and debug assertions are
2330 /// fn factorial(n: u32) -> u32 {
2331 /// (1..=n).product()
2333 /// assert_eq!(factorial(0), 1);
2334 /// assert_eq!(factorial(1), 1);
2335 /// assert_eq!(factorial(5), 120);
2337 #[stable(feature = "iter_arith", since = "1.11.0")]
2338 fn product<P>(self) -> P
2340 P: Product<Self::Item>,
2342 Product::product(self)
2345 /// Lexicographically compares the elements of this `Iterator` with those
2347 #[stable(feature = "iter_order", since = "1.5.0")]
2348 fn cmp<I>(mut self, other: I) -> Ordering where
2349 I: IntoIterator<Item = Self::Item>,
2353 let mut other = other.into_iter();
2356 let x = match self.next() {
2357 None => if other.next().is_none() {
2358 return Ordering::Equal
2360 return Ordering::Less
2365 let y = match other.next() {
2366 None => return Ordering::Greater,
2371 Ordering::Equal => (),
2372 non_eq => return non_eq,
2377 /// Lexicographically compares the elements of this `Iterator` with those
2379 #[stable(feature = "iter_order", since = "1.5.0")]
2380 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2382 Self::Item: PartialOrd<I::Item>,
2385 let mut other = other.into_iter();
2388 let x = match self.next() {
2389 None => if other.next().is_none() {
2390 return Some(Ordering::Equal)
2392 return Some(Ordering::Less)
2397 let y = match other.next() {
2398 None => return Some(Ordering::Greater),
2402 match x.partial_cmp(&y) {
2403 Some(Ordering::Equal) => (),
2404 non_eq => return non_eq,
2409 /// Determines if the elements of this `Iterator` are equal to those of
2411 #[stable(feature = "iter_order", since = "1.5.0")]
2412 fn eq<I>(mut self, other: I) -> bool where
2414 Self::Item: PartialEq<I::Item>,
2417 let mut other = other.into_iter();
2420 let x = match self.next() {
2421 None => return other.next().is_none(),
2425 let y = match other.next() {
2426 None => return false,
2430 if x != y { return false }
2434 /// Determines if the elements of this `Iterator` are unequal to those of
2436 #[stable(feature = "iter_order", since = "1.5.0")]
2437 fn ne<I>(self, other: I) -> bool where
2439 Self::Item: PartialEq<I::Item>,
2445 /// Determines if the elements of this `Iterator` are lexicographically
2446 /// less than those of another.
2447 #[stable(feature = "iter_order", since = "1.5.0")]
2448 fn lt<I>(self, other: I) -> bool where
2450 Self::Item: PartialOrd<I::Item>,
2453 self.partial_cmp(other) == Some(Ordering::Less)
2456 /// Determines if the elements of this `Iterator` are lexicographically
2457 /// less or equal to those of another.
2458 #[stable(feature = "iter_order", since = "1.5.0")]
2459 fn le<I>(self, other: I) -> bool where
2461 Self::Item: PartialOrd<I::Item>,
2464 match self.partial_cmp(other) {
2465 Some(Ordering::Less) | Some(Ordering::Equal) => true,
2470 /// Determines if the elements of this `Iterator` are lexicographically
2471 /// greater than those of another.
2472 #[stable(feature = "iter_order", since = "1.5.0")]
2473 fn gt<I>(self, other: I) -> bool where
2475 Self::Item: PartialOrd<I::Item>,
2478 self.partial_cmp(other) == Some(Ordering::Greater)
2481 /// Determines if the elements of this `Iterator` are lexicographically
2482 /// greater than or equal to those of another.
2483 #[stable(feature = "iter_order", since = "1.5.0")]
2484 fn ge<I>(self, other: I) -> bool where
2486 Self::Item: PartialOrd<I::Item>,
2489 match self.partial_cmp(other) {
2490 Some(Ordering::Greater) | Some(Ordering::Equal) => true,
2495 /// Checks if the elements of this iterator are sorted.
2497 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2498 /// iterator yields exactly zero or one element, `true` is returned.
2500 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2501 /// implies that this function returns `false` if any two consecutive items are not
2507 /// #![feature(is_sorted)]
2509 /// assert!([1, 2, 2, 9].iter().is_sorted());
2510 /// assert!(![1, 3, 2, 4].iter().is_sorted());
2511 /// assert!([0].iter().is_sorted());
2512 /// assert!(std::iter::empty::<i32>().is_sorted());
2513 /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
2516 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2517 fn is_sorted(self) -> bool
2520 Self::Item: PartialOrd,
2522 self.is_sorted_by(|a, b| a.partial_cmp(b))
2525 /// Checks if the elements of this iterator are sorted using the given comparator function.
2527 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2528 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2529 /// [`is_sorted`]; see its documentation for more information.
2531 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2532 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2533 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
2536 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>
2538 let mut last = match self.next() {
2540 None => return true,
2543 while let Some(curr) = self.next() {
2544 if compare(&last, &curr)
2545 .map(|o| o == Ordering::Greater)
2556 /// Checks if the elements of this iterator are sorted using the given key extraction
2559 /// Instead of comparing the iterator's elements directly, this function compares the keys of
2560 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
2561 /// its documentation for more information.
2563 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2568 /// #![feature(is_sorted)]
2570 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
2571 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
2574 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2575 fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
2578 F: FnMut(&Self::Item) -> K,
2581 self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2585 /// Select an element from an iterator based on the given "comparison"
2588 /// This is an idiosyncratic helper to try to factor out the
2589 /// commonalities of {max,min}{,_by}. In particular, this avoids
2590 /// having to implement optimizations several times.
2592 fn select_fold1<I, F>(mut it: I, mut f: F) -> Option<I::Item>
2595 F: FnMut(&I::Item, &I::Item) -> bool,
2597 // start with the first element as our selection. This avoids
2598 // having to use `Option`s inside the loop, translating to a
2599 // sizeable performance gain (6x in one case).
2600 it.next().map(|first| {
2601 it.fold(first, |sel, x| if f(&sel, &x) { x } else { sel })
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 impl<I: Iterator + ?Sized> Iterator for &mut I {
2607 type Item = I::Item;
2608 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2609 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2610 fn nth(&mut self, n: usize) -> Option<Self::Item> {